I want to have a derived class which has a default constructor that initializes the inheirited members.
Why can I do this
class base{
protected:
int data;
};
class derived: public base{
public:
derived(){ //note
data = 42;
}
};
int main(){
derived d();
}
But not this
class base{
protected:
int data;
};
class derived: public base{
public:
derived(): //note
data(42){}
};
int main(){
derived d();
}
error: class ‘derived’ does not have any field named ‘data’
An object can only be initialized once. (The exception is if you initialize it and then destroy it; then you can initialize it again later.)
If you could do what you're trying to do, then base::data could potentially be initialized twice. Some constructor of base might initialize it (although in your particular case it doesn't) and then the derived constructor would be initializing it, potentially for a second time. To prevent this, the language only allows a constructor to initialize its own class's members.
Initialization is distinct from assignment. Assigning to data is no problem: you can only initialize data once but you can assign to it as many times as you want.
You might want to write a constructor for base that takes a value for data.
class base{
protected:
int data;
base(int data): data(data) {}
};
class derived: public base{
public:
derived(): base(42) {}
};
int main(){
derived d{}; // note: use curly braces to avoid declaring a function
}
You need a base class constructor for this job. You can look for more explanation here -
Initialize parent's protected members with initialization list (C++)
Related
I'm trying to practice some polymorphism and i got into some issues.
Here's my code :
class A{ //the base
public:
A(){}
virtual void Log(){};
virtual ~A(){};
private:
protected:
int __value;
};
class B : public A{ //the derived
public:
B(int value):__value(value){} //here's the problem
void Log() override{
std::cout<<__value<<"\n";
}
~B(){};
};
At that lines the error said : "class 'B' does not have any field named '__value'". It does work if i will do it in this way :
class A{
public:
A(){}
virtual void Log(){};
virtual ~A(){};
private:
protected:
int __value;
};
class B : public A{
public:
B(int value){
__value=value;
}
void Log() override{
std::cout<<__value<<"\n";
}
~B(){};
};
I know what i've tried works while i'm accesing the private members, but I want to know if there is some way to make the first attempt work too.
Thanks!
C++ does not work this way. Only a class's constructor can initialize its members.
Only A's constructor can initialize its class member. That's what a constructor's job is. A derived class cannot initialize its base class's members, only it's own class members. A base class only initializes the base class's members. A derived class's constructor can initialize only its own class's members.
What you need to do is add a constructor to A, perhaps a protected constructor, with a parameter that initializes the class member with the parameter:
class A {
// ...
A(int value) : __value{value} {}
// ...
};
And have the derived class's constructor explicitly invoke this constructor.
B(int value) : A{value}
{
}
In some situations you can also delegate the constructor, as an alternative. This should be covered in the advanced C++ chapters of your C++ book.
P.S. You should use modern C++'s uniform initialization syntax, with {...} instead of (...). If you're using an older C++ book that doesn't cover uniform initialization syntax, you should get a more recent book.
I have the following class hierarchy, where the Base class depends on its derived class to supply it an argument in its constructor:
class Member
{
public:
Member(int v);
};
class Base
{
public:
Base(const Member& m);
};
class Derived : public Base
{
public:
Derived() : m_(123), Base(m_) // <- here is the problem
{
}
private:
Member m_;
};
The problem is, though, that in Derived's constructor, the Base constructor gets called first, when Derived's member variable m_ which it depends on isn't initialized yet.
Is there a way to force the compiler to call the constructor of m_ first or should I just rework my class hierarchy?
You can simulate initializing your member before the base class by making it it's own base class which you initialize first. You can wrap it in a simple class type and have Derived inherit privately from that type before Base. In the following example, Derived has a Member _m; which is initialized and then used to initialize Base.
class Member
{
public:
Member(int) {}
};
class Base
{
public:
Base(const Member&) {}
};
// The new wrapper
struct member_wrapper
{
member_wrapper(int v) : m_(v) {}
Member m_;
};
class Derived : private member_wrapper, public Base
{
public:
Derived() : member_wrapper(123), Base(m_)
{ }
};
Though in this case, since m_ is already a class type and Derived has no other members with that type, you can just inherit privately from Member directly. If you had a non-class type or multiple members of the same type that needed to be initialized before Base you would need to wrap them.
class Member
{
public:
Member(int) {}
};
class Base
{
public:
Base(const Member&) {}
};
class Derived : private Member, public Base
{
public:
Derived() : Member(123), Base(*this)
{ }
};
I have the following class:
class Base {
public:
Base(string name) {
agg = new Aggregate(name);
}
private:
Aggregate* agg;
};
Now I need to extend this class:
class Derived : Base {
public:
Derived(string name) : Base(name) {
agg2 = new Aggregate2(name);
}
private:
Aggregate2* agg2;
};
What I want is when I create a Base object, Aggregate needs to be created and when I create a Derived object only Aggregate2 should be created.
Now this is not happening because Aggregate its created inside the constructor which is called when I create a Derived object and like this Aggregate and Aggregate2 would be created.
I could move the creation to a different method and call that after creating the object.
Is there any other elegant way to do what I want ?
You may use the following:
class Base {
public:
explicit Base(string name) : agg(new Aggregate(name)) {}
protected:
Base() = default;
private:
std::unique_ptr<Aggregate> agg;
};
class Derived : Base {
public:
// implicit call to Base(), you may be explicit if you want
Derived(string name) : agg2(new Aggregate2(name)) {}
private:
std::unique_ptr<Aggregate2> agg2;
};
This is something you shouldn't do. If your second class isn't supposed to have the first Aggregate member, then the right way is to make two separate classes and not to use inheritance:
class Foo1 { ... };
class Foo2 { ... };
Now if you really have a reason to use inheritance you have a few options:
- Use a base class from which both Foo1 and Foo2 will derive. The base class only contains what is common to both Foo1 and Foo2. The Aggregates you need go separately into Foo1 and Foo2. (recommended)
- Let Foo1 have a union member (if you know the whys and wherefores of unions):
union Bla { std::unique_ptr<Agg1> a1; std::unique_ptr<Agg2> a2; };
And I should strongly emphasize that I can hardly think of an example where the second version is meaningful... Go for a separate base class!
Try this code
class Base {
public:
Base() { }
Base(string name) {
agg = new Aggregate(name);
}
void setName(string name) {
agg = new Aggregate(name);
}
private:
Aggregate* agg;
};
class Derived : Base {
public:
Derived(string name) {
agg2 = new Aggregate2(name);
}
private:
Aggregate2* agg2;
};
You can have a string type data member in Base class; which can be assigned value (same as name,in constructor) and you can access it in derived also(make it protected) to initialize agg2 in Derived class.
I would use a constructor overload for this:
class Base {
public:
Base(string name) : agg(new Aggregate(name)) {}
protected:
Base(Aggregate* agg) : agg(agg) {} //Base will take possession of the passed pointer.
private:
std::unique_ptr<Aggregate> agg;
};
class Derived : Base {
public:
Derived(string name) : Base(new Aggregate2(name)) {}
};
Note:
This assumes that Aggregate2 is derived from Aggregate. This assumption is based on the fact that removing ability of a base class in a derived class is at least a very strong code smell. So I concluded that both aggregates basically serve the same function, so that the second variable to hold the Aggregate2 instance is superfluous, and that Aggregate2 is a subclass of Aggregate to match behavior with relation.
I have a base class with a member variable (preferably private) and I need to enforce derived classes to initialize it with a value based on their implementation; much like a pure virtual function.
To clarify, I want to declare a member in Base, have derived classes initialize it, and if they don't they get a compiler error. In the following code, I declared default constructor of Base to be protected. Then declared default constructor of Derived to be private.
class Base {
private:
int _size;
protected:
Base(){}
/* pure virtual methods */
public:
Base(int size) : _size(size){} // must enforce derived to call this.
virtual ~Base(){}
/* more pure virtual methods */
};
class Derived : public Base {
private:
Derived() {}
public:
Derived(int size) : Base(size) {
//Base::Base(size);
}
};
int main()
{
Derived* d1 = new Derived(); // throws an error as needed:
// "Cannot access private member declared in class 'Derived'"
Derived* d2 = new Derived; // throws an error as needed:
// "Cannot access private member declared in class 'Derived'"
Derived* d3 = new Derived(5); // works as needed
return 0;
}
The problem with the above code is that if another definition of Derived doesn't hide the default constructor. I'm still stuck with an uninitialized Base::_size.
I don't know if there is another way to go about this other than inheritance, because I still need derived classes to implement their own behavior for several methods declared in Base.
Any pointers are appreciated.
After the confusion about calling a base class ctor and default ctors, maybe the solution is just to not have a default ctor in Base?
class Base {
private:
int _size;
public:
// no default ctor
Base(int size) : _size(size) {} // must enforce derived to call this.
virtual ~Base(){}
/* more pure virtual methods */
};
class Derived : public Base {
public:
// no default ctor
Derived(int size) : Base(size){
}
// examplary default ctor:
//Derived() : Base(42) {}
};
int main()
{
Derived d1; // error: no default ctor
Derived* d2 = new Derived; // same, but why use the free store?
Derived d3(5); // works as needed
Derived* d4 = new Derived(5); // same, but why use the free store?
return 0;
}
To be explicit about not having a default ctor, one could use
class Base {
/* ... */
Base() = delete;
/* ... */
};
Use a constructor
class Base1 {
protected:
Base1(int forward) {
thingYouWantToHide = forward;
}
private:
int thingYouWantToHide;
};
class Derived1: public Base1 {
public:
Derived1(): Base1(5) {}
};
class Base2 {
private:
int value;
protected:
Base2() {
value = calledToGet();
}
virtual int calledToGet() = 0;
virtual ~Base2() {} //shut compiler warnings up
};
class Derived2: public Base2 {
virtual int calledToGet() {
return 5;
}
};
int main(int,char**) {
Derived1 a;
Derived2 b;
return 0;
}
You may think Derived2 will work, but remember Derived2 is not constructed until Base2 is, so that virtual is an undefined reference when Base2 is being constructed.
You should use the first case, type-traits if it is a constant (static const) or fundamental to the type.
class Base {
public:
int a;
Base():a(0) {}
virtual ~Base();
}
class Derived : public Base {
public:
int b;
Derived():b(0) {
Base* pBase = static_cast<Base*>(this);
pBase->Base();
}
~Derived();
}
Is the call to the base class constructor necessary or does c++ do this automatically? e.g.
Does C++ require you to initialize base class members from any derived class?
The base class's constructor will automatically be called before the derived class's constructor is called.
You can explicitly specify which base constructor to call (if it has multiple) using initialization lists:
class Base {
public:
int a;
Base():a(0) {}
Base(int a):a(a) {}
};
class Derived {
public:
int b;
Derived():Base(),b(0) {}
Derived(int a):Base(a),b(0) {}
};
Base class constructors are called automatically (and before derived class contructors). So you need not, and must not, try to call base constructors manually.