1

When i have inheritance, does the compiler-generated functions that i usually get (constructor, destructor, assignment operator and copy constructor) are still generated for my classes?

Let's say i have this inheritance: A base class, B which inherits A (public) and C which public inherits B. My A class has no memory allocation or anything that requires a destructor to be implemented by me, and i'm not implementing a destructor there, when i compile my program will it still create an empty A::~A(){} ?

Same for B and C.. Thank you!

sepp2k
  • 363,768
  • 54
  • 674
  • 675
argamanza
  • 1,122
  • 3
  • 14
  • 36
  • If there's nothing else to prevent the compiler from generating the functions, then they will be created. But be careful as it might not behave as expected in all cases though, especially if you have a non-virtual destructor in the base class. – Some programmer dude Jun 25 '15 at 12:06

4 Answers4

1

The rule of 5 still applies to each of the classes, independent of their inheritence.

In other words, if B is derived from A, just because A defined their copy constructor, that doesn't affect the generation of Bs copy constructor.

You should, however, be mindful to define a virtual destructor for the base class if needed.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

Yes, of course. And the constructor/destructor chained calls are still present (i.e., C destructor will call B destructor which calls A destructor, same in the reverse order for constructors).

rems4e
  • 3,112
  • 1
  • 17
  • 24
0

Yes, Compiler always generates (constructor, destructor, assignment operator and copy constructor) for the classes , where user have not defined these functions explicitly.

mystic_coder
  • 462
  • 2
  • 10
0

Compiler inserts constructor, destructor,copy constructor and overloaded assignment operator in a class if it is not defined by the user.

But the most important thing is if user defines a parameterized constructor in a class,then compiler will not generate the default constructor and and object creation without any parameter will throw a linker error.

Say for example you have a class A

class A
{
int a;
public:
//.....
//some line of code 
//.....
}

If you don't provide any constructor, the compiler will generate a default constructor which does not takes any parameter A(){}.

But if by any chance you declare a parametrized constructor like

A(int i)
{
a = i;
}

The compiler doesn't generate any default constructor and your object creation with no parameter will fail.

 A a;    ---> This will fail.
 A b(10) ---> This will pass.

So thumb of rule is, if your are providing a constructor of your own, always provide the default constructor along with it.

Rndp13
  • 1,094
  • 1
  • 21
  • 35