Accessing members of derived classes

I have a base class and a class derived from it. In the example below, Frame_Pic is a derived class of Base_Pic, the details of which I have not included. Frame_Pic has members, vertical,horizontal, and corners which is not in the base class. Picture is an interface class and basically holds a pointer to Base_Pic.

When I try to assign new values to these in the reframe function below, I get an error stating that Base_Pic has no such data members.

The action, pic.p->vertical, will think I am accessing the base class. If I put these data members in the base class, the rest of my functions are written in a way that it will not accommodate this addition. How can I assign to these data members?

Picture frame(const Picture& pic, char v, char c, char h)
{
    Frame_Pic* temp = new Frame_Pic(pic.p);
    temp->vertical = v;
    temp->horizontal = h;
    temp->corners = c;
    Picture temp2(temp);
    return temp2;
}

void reframe(Picture& pic, char v, char c, char h)
{
    pic.p->vertical = v;
    pic.p->horizontal = h;
    pic.p->corners = c;
}

Answers


Sounds like you want to set items of a derived class while feeding a function a pointer to the base type. The way to do this is to create a virtual function in the base class and implement it in the derived class.

for instance...

virtual void BaseClass::SetupSomeStuff(...) {
}

void DerivedClass::SetupSomeStuff(...) {
your assignments here
}

Instead of accessing them directly, use your Picture interface to declare set and get methods (assuming both are needed) for those members, and implement them in the derived class.

Direct access to member variables does not behave polymorphically, hence your error.


You should rethink the way you wrote the functions and how the classes interact in general. Reframe might be a function member of Frame_Pic but its functionality has nothing to do with any instance of the class Frame_Pic. In fact, since all you can know for sure is that Picture holds a pointer to a Base_pic, it might as well hold a pointer to an instance of a different class that derives Base_pic that does not define members named vertical, horizontal or corners.

You should instead create a new Frame_pic instance like you did in the first function and set the pointer in Picture to that new instance. You might also want to mark these two functions as static if they are not, already.


Need Your Help

hide brightcove video and initiate onClick of <a> link

jquery brightcove

I have a brightcove video integration in my site and on mobile I would like to hide the video and then when the user clicks a link, it should open the video and start playing.