rocketjumper
rocketjumper

Reputation: 51

C++ Primer 5ed, 7_43

Hi I have a question when doing the exercise 7.43. The question goes: "Assume we have a class named NoDefault that has a constructor that takes an int, but has no default constructor. Define a class C that has a member of type NoDefault. Define the default constructor for C."

class NoDefault{
  public:
    NoDefault(int i){}
};

class C{

  private:
    NoDefault temp;
  public:
    C(int i):temp(i){}
};

int main(){
    C c;
    return 0;
}

Why C(int i):temp(i){} is not correct?

The error shows:

$ g++ -std=c++0x -o ex7_43 ex7_43.cpp
ex7_43.cpp: In function ‘int main()’:
ex7_43.cpp:16: error: no matching function for call to ‘C::C()’
ex7_43.cpp:12: note: candidates are: C::C(int)
ex7_43.cpp:7: note:                 C::C(const C&)

I know that C():temp(0){} compiles find.

Thanks!

Upvotes: 0

Views: 104

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

This constructor

C(int i):temp(i){}

is not the default constructor of the class. However inside main this declaration

C c;

requires existence of the default constructor of the class. So the compiler issues an error because there is no default constructor.

On the other hand this declaration

C():temp(0){} 

declares the default constructor that can be used in declaration

C c;

According to the C++ Standard (12.1 Constructors)

4 A default constructor for a class X is a constructor of class X that can be called without an argument.

You could define the default constructor with parameters but the parameters in this case shall have default arguments. For example

C(int i = 0):temp(i){}

The above constructor is the default constructor because it can be called without arguments.

And in the exersice there is written:

Define the default constructor for C

So you could define it either like

C():temp(0){} 

or like

C(int i = 0):temp(i){}

or even the following way

class C{

  private:
    NoDefault temp;
  public:
    C(int i);
};

C::C( int i = 0 ) :temp( i ) {}

That is to use the default argument in the definition of the contructor outside the class but before main.

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

You almost had it, but you did not define "the default constructor for C". You defined some other constructor. So, then, much like in NoDefault, C had no implicit default constructor and could not be instantiated in main through the declaration C c.

C() : temp(1337) {}

There you go.

Upvotes: 0

Related Questions