Reputation: 31
I know that generally it can't, but I was wondering if there was any code out there to allow me to have a function in the super class access a member of the sub class. There are four subclasses each with an int size variable, and for the function I need the size variable. I talked to a teacher about somehow using the friend code but she said that wouldnt work.
Upvotes: 0
Views: 689
Reputation: 1422
That's what virtual member functions are for:
struct Base {
virtual std::string child_name() = 0;
};
struct Derived1 {
virtual std::string child_name { return "Derived1"; }
};
struct Derived2 {
virtual std::string child_name { return "Derived2"; }
};
Please note that if you specify = 0 in the base class your base class will become "pure virtual" and not instantiable, so if you don't want this behaviour you will have to define a default implementation, that will be used also if a derived class does not define the virtual function.
IMPORTANT: Virtual functions should not be called in the constructor, otherwise you'll receive an exception (if the function is pure virtual) or an undesired behaviour (the default implementation will be called).
Upvotes: 0
Reputation: 4770
You can make a pure virtual function in the base class that returns the size. Then you can implement that function in the derived class which will return the size that is stored in the derived class.
Upvotes: 2