Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

School Assignment. C++ Book Example seems to have issues

Tags:

c++

The following code is part of a slide in my C++ Class. IntelliSence is giving me errors and I don't know why. Not sure why it doesnt like the Constructor and Destructor. Can Someone please Help?

class Vehicle {
     friend void guest();
 private:
     string make;
     string model;
     int year;
 public:
     void Vehicle();
     void Vehicle(string, string, int);
     void ~Vehicle();
     string getMake();
 }

 void guest() {
     cout << make;
 }

 1) IntelliSense: member function with the same name as its class must be a constructor
 2) IntelliSense: member function with the same name as its class must be a constructor
 3) IntelliSense: return type may not be specified on a destructor
like image 611
StephanM Avatar asked Aug 07 '12 15:08

StephanM


2 Answers

constructors and destructors don't have return types! Should be:

Vehicle();
Vehicle(string, string, int);
~Vehicle();

You need to pass an argument to your function:

void guest(const Vehicle &v)
{
    cout << v.make; //friend allows you to access 'make' directly
}

Of course you must change the friend declaration accordingly

And don't forget ; at the end of your class

EDIT

Full code that works:

class Vehicle {
    friend void guest(const Vehicle &v);
private:
    string make;
    string model;
    int year;
public:
    Vehicle() {}
    Vehicle(string make, string model, int year) : make(make), model(model), year(year) {}
    ~Vehicle() {}
    string getMake() const {return make;}
};

void guest(const Vehicle &v) {
    cout << v.make;
}



int main()
{
    guest(Vehicle("foo", "bar", 10));
    return 0;
}
like image 60
Andrew Avatar answered Nov 15 '22 02:11

Andrew


The error messages are actually pretty good in this case if you understand them.

void Vehicle();

because the "method" has the same name as the class, your Intellisense thinks it should be a construtor. It's right! Constructors don't have return types, so make it:

Vehicle();

Similarly:

void Vehicle(string, string, int);

also appears to be a constructor because the name of the "method" is the same as the class. Just because it has parameters doesn't make it special. It should be:

Vehicle(string, string, int);

Deconstructors don't have return types either, so

void ~Vehicle();

should be:

~Vehicle();
like image 42
James Webster Avatar answered Nov 15 '22 02:11

James Webster