C++ Abstract Class: Constructor Yes or No

Calling the Constructor for the Abstract Base class in C++

I know that the if I have an abstract class then I cannot create an object of abstract class type.

With one exception: An object of an abstract class can be created as a subobject of a derived-class object.

In fact, it must be created in that situation, because that's just how inheritance works in C++. An object of a derived class contains an object of the base class (or generally, objects of the base classes, because let us not forget that C++ also supports multiple inheritance).

The standard says this very clearly in §10.4/1:

An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it.

There you have it: instances of abstract classes may exist within this restriction. Therefore,

Base(string theName){name = theName);

Isn't this creating an object ??

It is a constructor like any other; it is used to create an object. The fact that the class is abstract doesn't matter, given the rule above.

Derived(string theName, int theAge):Base(theName) { age = theAge }

Isn't that also calling the default constructor for the Base ??

Yes, it is.

So, am I allowed to call a parametrized constructor but not the default one ?

A constructor in which all arguments are defaulted is a default constructor.

One more thing, if I have another function in the Base class other than the pure function, how can I call that function if I am not allowed to create an object for the Base class ?

If it's a public function, then anyone who has a derived-class object can call it (this includes the derived class itself). Additionally, anyone who accesses the derived-class object via a pointer or reference to the base class can call it. And of course, the base class itself can call it, too.

If it's a protected function, then the derived class and potential further derived classes can call it.

If it's private, then the base class itself can call it.

As we have established above, you do technically create an object for the base class, as a subobject inside of the derived-class object. So principally, the situation is not special just because the base class is abstract.


The thing to keep in mind here is that the technicalities of the language are defined so that all basic object-oriented features just work as expected. You don't have to worry about these things in your daily programming business.

Is it good to have a constructor in abstract class?

Yes, it's absolutely fine. Just because the constructor can only be called by derived classes doesn't mean it won't be useful. For example, you might have an abstract class which represents a named entity of some kind - it would make sense to take the name as a constructor parameter.

It would probably be worth making the constructor protected, to make it even more obvious that you can't just call it from elsewhere.

Note that there being a constructor (or multiple constructors) in an abstract class does force derived class constructors to go through it, but it doesn't force the derived classes to have the same constructor signatures. For example:

public abstract class NamedFoo
{
private readonly string name;
public string Name { get { return name; } }

protected NamedFoo(string name)
{
this.name = name;
}
}

public class DerivedFooWithConstantName
{
public DerivedFooWithConstantName() : base("constant name")
{
}
}

In this case the derived class constructor is "removing" a parameter (by providing a constant value as the argument to the abstract class constructor) but in other cases it could "add" parameters that it required, or have a mixture.

Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. Consider this:

abstract class Product { 
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}

public int mutiply(int val) {
return multiplyBy * val;
}
}

class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}

class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

NOTE: As there is no default (or no-arg) constructor in the parent
abstract class, the constructor used in subclass must explicitly call
the parent constructor.

Constructor of an abstract class in C#

Because there might be a standard way you want to instantiate data in the abstract class. That way you can have classes that inherit from that class call the base constructor.

public abstract class A{

private string data;

protected A(string myString){
data = myString;
}

}

public class B : A {

B(string myString) : base(myString){}

}

Can a constructor be abstract in C++?

Constructors can't be virtual.

Calling a virtual method in the base's constructor is problematic, because the derived object doesn't exist yet.

What you can instead do is provide a factory function that calls populate after constructing the object.

class Base
{
template <typename Derived, typename... Args>
static Derived make(Args&&... args)
{
Derived result(std::forward<Args>(args)...);
result.populate();
return result;
}
protected:
Base() = default;
virtual void populate() = 0;
};

Can I define a constructor in an abstract base class?

There are in fact 2 questions in one:

  • Can an ABC have a ctor?: Of course it can! Imagine you have an almost complete class, with private data and that only lacks one concrete method. This method should be pure virtual making the class abstract, but you still have to initialize class data in a ctor. The question suggested by Paul Rooney is an example for that
  • Can an interface have a ctor?: No, it cannot by definition. An interface is a special ABC that only contains pure virtual methods. It has no implementation not even a partial one, and as such needs no ctor. And you already noted that

A constructor cannot be a purely virtual function

TL/DR: if you are trying to add a constructor to your interface, then it is no longer an interface but a simple Abstract Base Class that is perfectly allowed to have one.

c++ abstract classes constructor calls

The constructor of the pure_virtual class is called when the constructor of inherit is called. So, when the line inherit temp; is executed, the constructor of the object is being called, because it is a derived class. Then the base class constructor is called first.

So in your case the output will be

Virtul class constructor called !
Derived class constructor called !

and because the void show() is virtual, the correct function is called, which is that of the inherit class.

What is the use of private constructor in abstract class in c#?

I can think of two uses:

Firstly, for chaining. You might have multiple protected constructors, but want to execute common code in all of them:

public abstract class Foo
{
protected Foo(string name) : this(name, 0)
{
}

protected Foo(int value) : this("", value)
{
}

private Foo(string name, int value)
{
// Do common things with name and value, maybe format them, etc
}
}

The second use would be to make it so that the only possible derived classes would be nested classes, which have access to private members. I've used this before when I want to enforce a limited number of derived classes, with instances usually exposed via the base class

public abstract class Operation
{
public static readonly Operation Add { get; } = new AddOperation();
public static readonly Operation Subtract { get; } = new SubtractOperation();

// Only nested classes can use this...
private Operation()
{
}

private class AddOperation : Operation
{
...
}

private class SubtractOperation : Operation
{
...
}
}

Whats the utility of public constructors in abstract classes in C#?

Absolutely correct. You should favor the protected constructor.

EDIT: no the compiler doesn't complain, but tools like FxCop (& Code Analysis) do. I believe there are some weird reflection tricks you can do with public constructors on abstract classes, but from a standpoint where you are merely providing base class functionality to other developers writing subclasses, stick with the protected constructor.



Related Topics



Leave a reply



Submit