Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".

class SuperClass
{
    public:

        SuperClass(int foo)
        {
            // do something with foo
        }
};

class SubClass : public SuperClass
{
    public:

        SubClass(int foo, int bar)
        : SuperClass(foo)    // Call the superclass constructor in the subclass' initialization list.
        {
            // do something with bar
        }
};

More info on the constructor's initialization list here and here.

Answer from luke on Stack Overflow
Top answer
1 of 10
1189

Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".

class SuperClass
{
    public:

        SuperClass(int foo)
        {
            // do something with foo
        }
};

class SubClass : public SuperClass
{
    public:

        SubClass(int foo, int bar)
        : SuperClass(foo)    // Call the superclass constructor in the subclass' initialization list.
        {
            // do something with bar
        }
};

More info on the constructor's initialization list here and here.

2 of 10
297

In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:

class Sub : public Base
{
  Sub(int x, int y)
  : Base(x), member(y)
  {
  }
  Type member;
};

If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:

class Sub : public Base
{
  Sub(int x, int y)
  try : Base(x), member(y)
  {
    // function body goes here
  } catch(const ExceptionType &e) {
    throw kaboom();
  }
  Type member;
};

In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.

🌐
TutorialsPoint
tutorialspoint.com › what-are-the-rules-for-calling-the-superclass-constructor-cplusplus
What are the rules for calling the superclass constructor C++?
#include <iostream> using namespace std; class MyBaseClass { public: MyBaseClass(int x) { cout << "Constructor of base class: " << x << endl; } }; //base constructor as initializer list class MyDerivedClass : public MyBaseClass { public: MyDerivedClass(int y) : MyBaseClass(50) { cout << "Constructor of derived class: " << y << endl; } }; int main() { MyDerivedClass derived(100); return 0; }
🌐
Quora
quora.com › In-C-how-can-I-properly-call-a-parent-class-constructor-in-the-derived-classs-constructor
In C++, how can I properly call a parent class constructor in the derived class's constructor? - Quora
Answer (1 of 6): You can invoke the parent constructor in the initialisation list of the derived class. e.g. [code]struct A { A(int a); }; struct B : A { B() : A(1) {} }; [/code]
🌐
Sololearn
sololearn.com › en › Discuss › 775101 › why-we-need-to-call-super-method-in-default-constructor-why-we-need-to-parent-class-constructor-why-it-is-compulsory
Why we need to call super() method in default constructor?? why we need to parent class constructor ?? why it is compulsory? | Sololearn: Learn to code for FREE!
Same for child and parent classes ;) ... when we put super() into a subclass it explicitly calls the superclass constructor. If we omit the call with super() there will be an implicit call to the Object class constructor(in superclasses).
🌐
Reddit
reddit.com › r/cpp_questions › calling inherited functions from base class constructor?
r/cpp_questions on Reddit: Calling inherited functions from base class constructor?
April 10, 2024 -

I was hoping that this construction would use the inherited function, but sadly calling the base class constructor calls the base class's function too. Is there a better way around this than just avoiding using the base class constructor?

#include <iostream>

class Parent 
{
public:
    Parent()
    {
        func();
    };

    virtual void func()
    {
        std::cout << "Parent" << std::endl;
    }
};

class Child : public Parent
{
public:
    Child() : Parent() {}

    void func()
    {
        std::cout << "Child" << std::endl;
    }
};

int main()
{
    Child child;

    return 0;
}
Top answer
1 of 3
4
As u/chrysante1 notes, “While constructing a Parent object, no Child object exists yet.”. To help avoid calling Child implementations of virtual functions from a Parent constructor, the dynamic type is Parent while the Parent constructor body executes. The virtual call mechanism works as it always does, but the dynamic type, the most derived class, is Parent. Especially in GUI programming there can be a need to do derived class specific things in a base class constructor. For example, a base class Widget may hold a handle to a system widget, and derived class Button needs to have that initialized with a call to system::create_button. A type safe way to arrange this is to have the handle, or a factory that can produce it, as a parameter of the Widget constructor, i.e. to pass the knowledge or ability as a parameter. And this is a FAQ item . Unfortunately that FAQ item starts with discussing two phase initialization as a solution, essentially calling a virtual init function after construction. It is technically a solution, and was used much in 1990's GUI frameworks, but it's not type safe and not exception safe, and I don't recommend it. Bjarne discusses init methods in the appendix on exception safety in the 3rd edition of "The C++ Programming Language" , and he doesn't recommend it either: ❝this two-stage construction technique doesn’t deliver its expected benefits. It can also be a source of problems.❞ Back in 2010 I thought the FAQ maintainer (Marshall Cline) did a wise thing by including also a discussion of two phase initialization as a solution, to let people just choose freely whatever worked best for them. We were stuck in the perception that all that 1990's code couldn't have been entirely wrong. That there had to be some advantage to the madness. Now I don't see that as wise: two phase initialization is the problem that e.g. parameter passing solves. A concrete example of passing the requisite information up the base class chain via parameters: #include namespace system_gui { class System_widget { public: virtual ~System_widget() {} }; class System_button: public System_widget {}; using Handle = void*; } // namespace system_gui namespace gui { namespace api = system_gui; class Widget // TODO: add that it's non-copyable, add move support, add ownership, etc. { api::Handle m_handle; protected: virtual ~Widget() {} // Gets handle as param instead of (not possible in C++) calling a virtual method producing it. Widget( const api::Handle handle ): m_handle( handle ) {} public: auto handle() const -> api::Handle { return m_handle; } }; class Button: public Widget { protected: Button( const api::Handle handle ): Widget( handle ) {} public: Button(): Widget( new api::System_button ) {} }; } // namespace gui #include // puts #include // For `typeid`. namespace app { void run() { auto widget = gui::Button(); auto p_api_object = reinterpret_cast( widget.handle() ); puts( typeid( *p_api_object ).name() ); // "System_button" } } // namespace app auto main() -> int { app::run(); }
2 of 3
2
Making the class pure virtual shows why :5:16: warning: call to pure virtual member function 'func' has undefined behavior; overrides of 'func' in subclasses are not available in the constructor of 'Parent' [-Wcall-to-pure-virtual-from-ctor-dtor] 5 | Parent() { func(); }; |
🌐
Unreal Engine
forums.unrealengine.com › development › programming & scripting › c++
[4.6]Super::Constructor called automatically? - C++ - Epic Developer Community Forums
December 7, 2014 - Hello, when using the 4.6 constructors like this: AExampleActor::AExampleActor() { } I cannot call the constructor of the superclass like this: AExampleActor::AExampleActor() : Super() { } because of this error: n…
🌐
Cplusplus
cplusplus.com › forum › beginner › 144422
Calling constructor of parent class by c - C++ Forum
Oh, thank you guys, I think I misunderstood something in my book... So it doesn't matter which derived constructor I call, it's always the default base constructor() that is called as long as I do not call another one explicitly like this: child::child() : parent(int specific_arguments) Thank's for the fast and good support!
🌐
Cplusplus
cplusplus.com › forum › general › 97350
Calling Base Class Constructors From De - C++ Forum
There is no easy way to do this, as classes can be derived from multiple other classes. There is no way to tell with a single command in what super class you want to call the constructor.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjava › what is the purpose of super() in a class constructor method?
r/learnjava on Reddit: What is the purpose of super() in a class constructor method?
May 20, 2020 -

Would it be accurate to say that the word super makes the class inherit all the methods of its parent class which is Object? Is the line super(); responsible for Java knowing that every instance of my class is also an Object? Does the super(); line do anything else in this case?

Just in case this needs clarification, this is what i'm talking about

public class Product {
       int id;
       String name;

public Product(int id, String name) {
	super();
	this.id = id;
	this.name = name;
   }
🌐
Unreal Engine
forums.unrealengine.com › development › programming & scripting › c++
C++ call parent-constructor manually? - C++ - Epic Developer Community Forums
May 26, 2016 - I would like to have full control over when the parent-constructor is called (it seems that UE4 calls it automatically and before the child-constructor). I have a piece of code in BaseEnemy (that inherits from BaseCharacter) that must be performed in the constructor, but before the BaseCharacter-constructor runs.
🌐
Reddit
reddit.com › r/unrealengine › what does the " : super(objectinitializer)" do? and what is it called in c++?
r/unrealengine on Reddit: what does the " : Super(ObjectInitializer)" do? and what is it called in C++?
March 13, 2022 - That just calls constructor of the base class. In this case APlayerController. This is the code that runs when the class is created. Calling superclass constructor ensures that the stuff that needs to happen still even though you are creating you’re own constructor.
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit9-Inheritance › topic-9-4-super.html
9.4. super Keyword — CSAwesome v1
Add another subclass called Vegan that inherits from the Student class. Add a Vegan contructor that takes a name as an argument and passes it to the super constructor. Override the getFood() method in Vegan to call the superclass getFood() but add a “No “ in front of it and then say “but “ and add a vegan food.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Calling Constructor of the Base Class - Programming - Arduino Forum
November 2, 2017 - Hi all. Continuing my journey to “upgrade” my programming skills from Good Old C to C++. Got a question about calling a base class’s constructor from the constructor of a derived class. This is the method I’ve seen: class derivedClass : public baseClass { public: derrivedClass(baseParam1, baseParam2, derrivedParam1, derrivedParam2) : baseClass(baseParam1, baseParam2) { // derivedClass Constructor body here } /* Rest of derrivedClass definition here */ }; ...
🌐
ESLint
eslint.org › docs › latest › rules › constructor-super
constructor-super - ESLint - Pluggable JavaScript Linter
/*eslint constructor-super: "error"*/ class A { constructor() { } } class B extends C { constructor() { super(); } } ... If you don’t want to be notified about invalid/missing super() callings in constructors, you can safely disable this rule.
🌐
Starling-framework
forum.starling-framework.org › d › 22605-parent-constructor-called-even-if-super-in-child-class-is-not-called
Parent constructor called even if super() in child class is not called - Starling Forum
Something went wrong while trying to load the full version of this site. Try hard-refreshing this page to fix the error · This seams a little strange to me. I thought if you do not call super in constructor that parent constructor will not be called. If I have: · In this case constructor ...
🌐
Sololearn
sololearn.com › en › Discuss › 3039747 › can-i-call-derived-class-constructor-before-base-class-constructor-in-c
Can I call derived class constructor before base class constructor in c++? | Sololearn: Learn to code for FREE!
proGAMBLER No. You cannot call the constructor of a derived class before the constructor of the base class. Why do you want to do that though? I don't see any reason for calling the constructor of the base class after.
🌐
SAP Community
community.sap.com › t5 › application-development-discussions › call-the-super-constructor-after-calling-the-other-method-oop › m-p › 12415020
Solved: Call the super constructor after calling the other... - ...
September 14, 2021 - To create an instance of a class, the constructor method is implicitly called. In the case of inheritance, as in your example, where a class has a super class. The constructor of the super class must always be run before any instance methods ...
🌐
Unity
discussions.unity.com › questions & answers
Calling a parent constructor after the child's in C# - Questions & Answers - Unity Discussions
April 11, 2012 - In UnityScript, you can call a parent’s constructor whenever you want inside a child constructor with super(). It let’s you process stuff in the child constructor before you call the parent constructor. (How) can I do that in C# (and Boo) ? The default behaviour calls the parent constructor before anything happens in the child constructor.
Top answer
1 of 7
20

If the base class constructor takes at least one argument, you could use a helper function like this:

int DoStuffBeforeCtorAndForwardInt(int arg, Foo foo)
{
    DoStuff(arg, foo);
    return arg;
}

MyClass::MyClass(int arg, Foo foo)
    : Base(DoStuffBeforeCtorAndForwardInt(arg, foo))
{
   // ...
}

If you want to default-initialize the base class, you could use the copy-ctor to copy a default initialized base class instance:

Base DoStuffBeforeCtorAndReturnDefaultBase(int arg, Foo foo)
{
    DoStuff(arg, foo);
    return Base();
}

MyClass::MyClass(int arg, Foo foo)
    : Base(DoStuffBeforeCtorAndReturnDefaultBase(arg, foo))
{
   // ...
}

Or, if Base doesn't have to be the first base class, you could derive MyClass from a helper class:

MyClass::MyClass(/* ... */)
    : DoStuffHelperClass(/* ... */),
    Base(/* ... */)
{
   // ...
}

All of the above require that the "stuff" you do does not depend on the object that's about to be initialized (i.e. the functions can't safely be member functions and you cannot safely pass this as an argument to them either).

That means you can do some logging or similar, but then again you could also do that after the base class has been initialized.

(EDIT except with the DoStuffHelperClass solution, you can of course have members in DoStuffHelperClass, access them and what not)


Although I have to say that I can't recall ever using/needing/wanting something like that. It's quite probable that there is another (preferable) solution for what you're trying to do.

2 of 7
10

Use the base-from-member idiom to run your code before the ctor of the "real" base class (which is Base):

struct Base {
  Base(string, int);
};

struct DerivedDetail {
  DerivedDetail() {
    value = compute_some_value();
    value += more();
    value += etc();
    other = even_more_code(value);
  }
  string value;
  int other;
};

struct Derived : private DerivedDetail, Base {
  Derived() : Base(value, other) {}
  // In particular, note you can still use this->value and just
  // ignore that it is from a base, yet this->value is still private
  // within Derived.
};

This works even if you don't have actual members you want in DerivedDetail. If you give more specifics on what you must do before the Base's ctor, then I can give a better example.

🌐
CodeHS
codehs.com › textbook › apcsa_textbook › 9.2
Textbook: AP Computer Science A Textbook | CodeHS
9.2 Writing Constructors for Subclasses · super Keyword · The Object Class · Student Subclass · Shape Class · Implicit Call to Super · Check Your Understanding · Exercise: Clothing Store · 9.3 Overriding Methods · 9.4 super Keyword · 9.5 Creating References Using Inheritance Hierarchies ·