kjh
kjh

Reputation: 3411

Derived Class Constructor Calls

If I have a base class:

class Base{
  ...
};

and a derived class

class Derived : public Base{
  ...
}

does this derived class always call the default constructor of the base class? i.e. the constructor that takes no parameters? For example If I define a constructor for the base class:

Base(int newValue);

but I do not define the default constructor(the parameterless constructor):

Base();

(I recognize this is only a declaration and not a definition) I get an error, until I define the default constructor that takes no parameters. Is this because the default constructor of a base class is the one that gets called by a derived class?

Upvotes: 6

Views: 24456

Answers (4)

sanjeev
sanjeev

Reputation: 600

Yes, by default, the default constructor is called. But in case your base class has paramterized constructor then you can call non default constructor in two ways.:

option 1: by explicitly calling a non-default constructor:

class Derived : public Base{
Derived() : Base(5) {}
};

Option 2:

in base class constructor set the parameter default value to 0, so it will 
 act as default as well as paramterized constructor both

for example:

class base
{ public:
base(int m_a =0){} 
};

 class Derived
 { public:
 Derived(){}
};

above approach will work fine for both paramterized constructor calling and default constructor calling.

Upvotes: 1

Daemon
Daemon

Reputation: 1675

By default Compiler provide three defaults:

  1. Default (Parameterless) Ctor

  2. Copy Ctor

  3. Assignment operator

In case if you yourself provide parameterised Ctor or Copy Ctor then compiler does not give default Ctor, so you explicitly have to write Default Ctor.

When we create a Derived class object it by defaults search for Base's default Ctor and if we have not provided it then compiler throws error. However we can make Derived class Ctor to call our specified Base Ctor.

class Base {
public:
Base(int x){}
};

class Derived {
public:
Derived():Base(5){}             //this will call Parameterized Base Ctor
Derived(int x):Base(x){}        //this will call Parameterized Base Ctor
}

Upvotes: 1

nikhil
nikhil

Reputation: 11

The reason why default constructor is called is that in case if you have created any object and at that instance you have not passed arguments (you may want to initialize them later in the program). This is the most general case, that's why calling default constructor is necessary.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258678

Yes, by default, the default constructor is called. You can go around this by explicitly calling a non-default constructor:

class Derived : public Base{
    Derived() : Base(5) {}
};

This will call the base constructor that takes a parameter and you no longer have to declare the default constructor in the base class.

Upvotes: 10

Related Questions