Constructor Confusion

Can someone explain why the car's default constructor is not being called?


main:
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
#include <iostream>
#include "Car.h";

using namespace std;
Car::Car(){
cout<<"Car's defautlt constructor called"<< endl;
 }

Car::Car(double d){
cout<<"Car("<<d <<") constuctor called"<< endl;
 }
Car::~Car(){
    cout<<"Car's destructor called"<<endl;
    }


int main()
{
//why doesn't the next line seem to do anything
Car c();

//this next line works fine
Car c2(1.2);

return 0;
}



my Car header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef CAR_H_INCLUDED
#define CAR_H_INCLUDED

class Car{
public:
   Car ();
   Car (double m);
   ~Car();
private:
    double mpg;
    };

#endif // CAR_H_INCLUDED

closed account (z05DSL3A)
The compiler is probably giving a warning about Car c();, try changing it to Car c;

Line 20 doesn't create an object c of type Car, it declares a function called 'c' that returns a Car and takes no parameters. Remove the parentheses.
It is because Car c(); looks like a prototype for a function named 'c', taking no arguments, that returns a 'Car'. Hence, that's what the compiler thinks it is.

[edit] argh, too late... ;-)
Last edited on
In main, line 20, you don't have parameters to the constructor method. So, you should not use "()":
Car c;

One more thing, remove the ";" from the end of line 2. This will cause warnings.
thanks!
Topic archived. No new replies allowed.