tesla1060
tesla1060

Reputation: 2765

C++ is that possible to initialize base class' base class?

I am trying out the below snippet,

#include <string>

class A {
protected:
    std::string name;
public:
    A(std::string name):name(){}
};

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

class C: public B {
public:
    C(): A("C"){} //<-- this is not allowed, but I want to make C has its own name
};

Obviously, this is not allowed, what is the best way I can achieve this?

Upvotes: 1

Views: 100

Answers (3)

Murat Hepeyiler
Murat Hepeyiler

Reputation: 456

You can like that,

#include <string>

class A {
protected:
    std::string name;
public:
    A(std::string name) : name(name){} // also here a mistake 
};

class B: public A {
public:
    B() : A("B") {}
protected:
    B(std::string str) : A(str) {}
};

class C: public B {
public:
    C(): B("C"){}
};

The reason why I have placed B(std::string str) in the protected area is only derived class can access that area but the clients do not. I think that you want that if the class created from client base class is named as A.

Upvotes: 1

user1143634
user1143634

Reputation:

One way to achieve this is to use virtual inheritance:

class A {
protected:
    std::string name;
public:
    A(std::string name):name(){}
};

class B: public virtual A { // note the "virtual" keyword here
public:
    B() : A("B") {}
};

class C: public B {
public:
    C(): A("C") {} 
};

This does what you asked for, but I am not sure this is what you need.

You should consider just adding a separate constructor to class B (probably protected one) that does such initialization.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234665

Rewriting B's constructor

B(const std::string& name = "B") : A(name) {}

is one way. Here I'm equipping it with a default value, so it still acts as the default constructor.

Upvotes: 4

Related Questions