Why can't I declare class objects right after I make the class?
Nov 10, 2014 at 3:24am UTC
The header file below is what I am using for another file, but I'm a little bit confused about why I can't declare class objects right after I define a class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#ifndef CARPROGRAM_H
#define CARPROGRAM_H
using namespace std;
class Car
{
int yearModel;
string make;
int speed;
public :
Car (int x)
{
yearModel = x;
speed = 0;
}
int getYearModel()
{
return yearModel;
}
string getMake ()
{
return make;
}
int getSpeed ()
{
return speed;
}
int accelerate ()
{
speed += 5;
}
int brake ()
{
speed -= 5;
}
}object; //compiler says there's an error here
#endif
Nov 10, 2014 at 3:28am UTC
Why not just make the object where you are going to use it?
1 2 3 4 5 6
#include "car.hpp"
int main()
{
Car object;
}
*Edit as mentioned by mobotus you never created a constructor with no arguments.
Last edited on Nov 10, 2014 at 3:48am UTC
Nov 10, 2014 at 3:42am UTC
Because your constructor takes an argument.
There is no Car() there is only a Car(int), but you try to make an object with without arguments.
Topic archived. No new replies allowed.