user1065101
user1065101

Reputation:

Only declaring a default constructor in C++

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?

Upvotes: 1

Views: 812

Answers (2)

Raul Andres
Raul Andres

Reputation: 3806

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

Upvotes: 1

djee
djee

Reputation: 43

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.

Upvotes: 0

Related Questions