Reputation: 342
In my application I have a list of objects of my base class type. Each one of the base classes can have multiple configurations (the derived class) and I've been trying to figure out how pass the base class into the derived class so I don't need to reinitialize the values every time. I know I can do it the following ways, but I'm curious if there's an easier/less clunky way since the base class in my code takes a while to initialize and has a lot of features.
Simple Example:
class Base {
public:
Base(int a, int b) : a(a), b(b) {}
protected:
int a;
int b;
};
class Derived : public Base {
public:
Derived(int c, int d, Base base) : c(c), d(d) {
this->a = base.a;
this->b = base.b;
}
private:
int c;
int d;
};
OR (trying to avoid this due to high overhead)
class Base {
public:
Base(int a, int b) : a(a), b(b) {}
protected:
int a;
int b;
};
class Derived : public Base {
public:
Derived(int c, int d, const Base &base) : Base(base), c(c), d(d) {}
private:
int c;
int d;
}
Upvotes: 0
Views: 359
Reputation: 1103
the two are both wrong: in Derived class you can not acess the protected member of the base class throngh a base object. To solve your problem,you can define copy construct for your base class and use it to initialize your base part of the Derived class
Upvotes: 0
Reputation: 180415
If Base
has a copy constructor then you can simply use:
class Base {
public:
Base(int a, int b) : a(a), b(b) {}
Base(const Base& base) : a(base.a), b(base.b) {} // make your own or use the default
protected:
int a;
int b;
};
class Derived : public Base {
public:
Derived(int c, int d, const Base& base) : Base(base), c(c), d(d) {}
private:
int c;
int d;
}
Upvotes: 4