Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a time when a superclass's constructor is not called in C++?

This question got me in an interview. If B is A's subclass. When constructing B, is there a time when A's constructor is not called?

EDIT: I told the interviewer that I couldn't think of such case because I thought it would only make sense for a superclass to be constructed properly before constructing the subclass.

like image 700
Russell Avatar asked Apr 27 '11 21:04

Russell


3 Answers

I suppose you could do something that throws an exception while generating the parameters for a non-default constructor for A in B's initialization list?

You can see below that the constructor for A is never called because an exception occurs in the parameters generation for it

#include <iostream>

using namespace std;

int f()
{
    throw "something"; // Never throw a string, just an example
}


class A
{
public:
    A(int x) { cout << "Constructor for A called\n"; }
};


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


int main()
{
    try 
    {
        B b;
    }
    catch (const char* ex) 
    {
        cout << "Exception: " << ex << endl;
    }
}
like image 26
jcoder Avatar answered Oct 27 '22 01:10

jcoder


Virtual Inheritance.

struct B {...};
struct D1 : virtual B {...};
struct D2 : virtual B {...};
struct Child : D1, D2 {...};

Normally the constructor B() should have been called twice, but it will be called only once.

like image 34
iammilind Avatar answered Oct 27 '22 00:10

iammilind


One possible instance is when both A and B have no user-declared constructors and an instance of B is being value-initialized.

A and B both have implicitly declared constructors which wouldn't be used in this initialization.

Similarly if A has no user-declared constructor but appears in the member initializer list of a constructor of B but with an empty initializer then A will be value-initialized when this constructor of B is used. Again, because A has not user-declared constructors the value-initialization doesn't use a constructor.

like image 82
CB Bailey Avatar answered Oct 27 '22 01:10

CB Bailey