Complete the code to call the base class constructor from the derived class.
class Base { public: Base() { std::cout << "Base constructor\n"; } }; class Derived : public Base { public: Derived() : [1]() { std::cout << "Derived constructor\n"; } }; int main() { Derived d; return 0; }
The derived class constructor calls the base class constructor by naming the base class Base() in the initializer list.
Complete the code to call the parameterized base class constructor from the derived class.
class Base { public: Base(int x) { std::cout << "Base constructor with " << x << "\n"; } }; class Derived : public Base { public: Derived(int y) : [1](y) { std::cout << "Derived constructor with " << y << "\n"; } }; int main() { Derived d(5); return 0; }
The derived class constructor calls the base class constructor with an argument by naming the base class Base(y) in the initializer list.
Fix the error in the constructor calling order by completing the code.
class A { public: A() { std::cout << "A constructor\n"; } }; class B : public A { public: B() { std::cout << "B constructor\n"; } }; class C : public B { public: C() : [1]() { std::cout << "C constructor\n"; } }; int main() { C c; return 0; }
Class C inherits from B, so its constructor should call B's constructor explicitly if needed. The base class A's constructor is called automatically by B's constructor.
Fill both blanks to create a constructor in Derived that calls the Base constructor with an argument and initializes member x.
class Base { public: Base(int a) { std::cout << "Base constructor with " << a << "\n"; } }; class Derived : public Base { int x; public: Derived(int a, int b) : [1](a), [2](b) { std::cout << "Derived constructor with " << b << "\n"; } }; int main() { Derived d(10, 20); return 0; }
The constructor initializer list first calls the base class constructor Base(a), then initializes the member variable x(b).
Fill the blanks to complete the constructor calling order in multiple inheritance.
class A { public: A() { std::cout << "A constructor\n"; } }; class B { public: B() { std::cout << "B constructor\n"; } }; class C : public A, public B { public: C() : [1](), [2]() { std::cout << "C constructor\n"; } }; int main() { C c; return 0; }
The constructor of C calls the constructors of both base classes A and B, in the order the bases appear in the inheritance list (A before B).