axis
axis

Reputation: 872

Making initialization lists work with inheritance in C++

The following piece of code gets compiled under g++ 4.6.3 for Linux

#include <iostream>

class A {
  public:  

    int x;
    std::string c;

    A(int x,std::string c):x(10),c("Hi"){
    }

    ~A(){
      std::cout << "Deleting A()" << std::endl;
    }
};

class B : public A {
  public:

    B():A(20,"Hello"){
    }

    ~B(){
      std::cout << "Deleting B()" << std::endl;
    }
};

int main(){
  B o;
  std::cout << o.x << std::endl;
  std::cout << o.c << std::endl;
  return(0);
}

but it does not do what is supposed to do, the type B is not able to change the values of that 2 variables that it inherit from A.

Any explanations about why this doesn't work properly ?

Upvotes: 3

Views: 16031

Answers (3)

enobayram
enobayram

Reputation: 4698

OK, I don't understand what exactly you want and why, but here's a suggestion, with C++11, you can do the following:

struct Base {
        int a;
        float b;
};

struct Derived: public Base {
        Derived(): Base{1,1.0} {}
};

int main() {
        Derived d;
}

as long as the base is a POD type.

I'd still prefer A(int x = 10,std::string c = std::string("Hi")):x(x),c(c){...} though.

IMHO, you need to review if you really need that much control over your base class in the first place. You're not really supposed to micro-manage a class from the outside like that, it's an indication of a flaw in your class hierarchy.

Upvotes: 1

There seems to be some confusion about what you want and how to achieve this. If I got you right this is what you want:

class A {
  public:  

    int x;
    std::string c;
    //default initization of A
    A():x(10), c("Hi") {}

    //initializing the values of A via parameters
    A(int x,std::string c):x(x),c(c){}

    ~A(){
      std::cout << "Deleting A()" << std::endl;
    }
};

class B : public A {
  public:

    B():A(20,"Hello"){
    }

    ~B(){
      std::cout << "Deleting B()" << std::endl;
    }
};

So in this example:

int main()
{
    A a;
    A a1(2, "foo");
    B b;
    return 0;
}
  • a.x == 10, a.c == "Hi"
  • a1.x == 2, a1.c == "foo"
  • b.x == 20, b.c == "Hello"

Upvotes: 1

Qaz
Qaz

Reputation: 61920

Your base constructor takes those values...and completely disregards them!

Change this:

A(int x,std::string c):x(10),c("Hi"){}

to this:

A(int x,std::string c):x(x),c(c){}

Upvotes: 5

Related Questions