Derived Class Constructors

What happens if we dont specify any constructor in the derived class and try to create an object of the derived class as.

Derived d1;

Is the no arguement constructor in the Base class called.
and further more
what if we try this

Derived d2(10);

Is the one arguement constructor of base class called
http://ideone.com/Dqv1j
That's all you have to do to know..

If you do want Derived(int) to call Base(int), you can say so. See http://www.cprogramming.com/tutorial/initialization-lists-c++.html
When you don't define any constructor a default one is provided to you by the compiler so
Derived d1; would use that one. That means that each data member is initialized to its default value (if there is one) otherwise it's uniitialized (like int, float etc). It will use Base class default constructor also.

But when you will try
Derived d2(10);
default constructor wont do so compiler will complain.

For your information only default constructor (that without arguments), copy constructor (that with an argument of the same type class object) and assignment operator (operator=) are provided if not defined by the programmer.
Read up on it TS, along with name hiding and name overriding. Just remember that once you declare any consructor, even a copy constructor, the compiler no longer provides a default constructor for you.

1
2
3
4
5
6
7
8
struct Foo {
	Foo(const Foo& f);   // copy constructor declared 
};

int main () {
      Foo f;     // error, no default constructor defined!!!
      return 0;
}
Topic archived. No new replies allowed.