cody
cody

Reputation: 157

Explanation of some simple constructor code

I'm slightly confused on what happens if I do the following:

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

class b: public a{
};

int main(){
  b  b1;
}

Since class b has no constructor, what constructor does it use? Does it use default constructor of a? Or its very own compiler generated one?

Upvotes: 2

Views: 120

Answers (5)

Tony Delroy
Tony Delroy

Reputation: 106076

Since class b has no constructor, what constructor does it use? Does it use default constructor of a? Or its very own compiler generated one?

This is a little bit trickier than it may at first seem.

In terms of the C++ Standard, classes get compiler-generated constructors taking no arguments when the programmer doesn't explicitly specify a constructor. Conceptually, b gets such a default constructor which in turn invokes the constructor of a.

At another level, in an optimising compiler neither constructor has anything to do - they may (or may not) be completely eliminated and "not exist" even as an empty function. So - at this level - talk about b's constructor calling a's constructor is just nonsense.

IMHO, it's important to understand both aspects.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308111

There are two constructors that will be called - first constructor a for the base class initialization, then constructor b. Since you didn't define a constructor for b the compiler generated a default one for you. Since your b class doesn't have any members that need constructing, that default constructor will be empty.

Upvotes: 5

Pubby
Pubby

Reputation: 53017

class b will have a default constructor generated by the compiler. Because b inherits a, the order will first construct a, and then b.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283614

It has a compiler-generated "defaulted" default (zero argument) constructor and a compiler-generated "defaulted" copy constructor. It also has a compiler-generated "defaulted" move constructor, if your compiler supports it.

Upvotes: 4

antlersoft
antlersoft

Reputation: 14786

Class b will have a compiler-generated constructor, which will in turn call the constructor of a.

Upvotes: 1

Related Questions