0

I wish to know if i only declare (and not define) a default constructor in a derived class, why doesn't the base class constructor gets invoked when i create an object of derived class?

Also is it a common practice to only declare default constructors? If yes, what are advantages of the same?

class A
{
  private:
  A() {}
}

class B : public A
{
  B();
}

doesn't give compilation errors, but

class B : public A
{ 
  B() {}
}

gives the error :- In constructor B::B(): error: A::A() is private.

What is the justification for the same?

  • See answers to the question: http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules Although I know its not the default constructor but it might provide some insight on constructor invocation. – praxmon Feb 14 '14 at 06:39

2 Answers2

1
class B : public A
{
  B();
}

In this case, compiler accepts that because you could implement B() using any public or protected constructor for A. It is not implementation, so at this point you are not using A().

class B : public A
{
  B(){};
}

Here you're implicitly using empty A constructor, that is declared private, so is illegal.

Declaring all constructor private disallows derivation. I suppose it's useful for someone in some circunstances

Raul Andres
  • 3,766
  • 15
  • 24
  • But my code doesn't have any public/protected constructors for A. Does it mean that i can't create an object of class B? –  Feb 14 '14 at 08:41
  • You're code don't even allows you to instantiate A objects. No public constructor and no static factory functions. But you can still derive A and access to the public and protected static members, if any. – Raul Andres Feb 14 '14 at 08:51
0

Can you provide an example? It seems strange that the code compile and runs if you really declare but not define the constructor. You should have an undefined reference to the derived constructor.

Usually you would only declare-and-not-define a member function that you want to prevent being used. For example, you can declare-and-not-define a copy constructor (privately) to prevent the object from being copied. The "prevention" here is actually achieved through an undefined reference compilation error.

djee
  • 43
  • 6
  • `base *b = new base(); ((derived*)b)->some_fn_of_derived();` will compile and run if `derived`'s `ctor` is declared but not defined. I'm not saying it's safe or 'best practice' but C/C++ will allow you to do a lot of things that don't really 'make since' (though once you use the language more you understand why and how it 'could' be useful)... – txtechhelp Feb 14 '14 at 06:57
  • It doesn't run. It doesn't link. It passes compilation. – selalerer Feb 14 '14 at 08:27