• Advertisement
Sign in to follow this  

Accessing base class functions

This topic is 4736 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is it possible, when dealing with an derived object, to call the functions for the base class?
class A{
public:
     // data members

     virtual void serialize()
     {
          // code
     }

};

class B : public A
{
public:
     void serialize()
     {
          // code
     }
};

int main()
{
     B bObject;

     // call serialize for class A and B here


return 0;
}


Because I'm a little lazy and have a base class with about 17 data members, is it possible to call A::serialize and then B::serialize, both on the B object? I mean, I doubt it, because of, you know, typing and all, but, good to check anyway.

Share this post


Link to post
Share on other sites
Advertisement
Might you be looking for...

bObject.Serialise();
dynamic_cast<A>(bObject).Serialise();

? You should even be able to get away with a static_cast<A>, depending on whether B is inherited from A, which in your example it is... So yeah, static_cast should work...

bObject.Serialise()
static_cast<A>(bObject).Serialise();

Or am I missing your point here?

CJM

Share this post


Link to post
Share on other sites
Sure, just specify the class for which you want to call the method like this:


class Base {
public:
virtual void foo() {}
};

class Derived : public Base {
public:
virtual void foo() {}
};

int main() {
Derived x;

x.Base::foo();
x.Derived::foo();
}



-Markus-

Share this post


Link to post
Share on other sites
...or did you intend to automatically call A::serialize() upon B::serialize() being called. That's the responsibility of B's implementation, meaning you should do it like this


//
// B's serialize() implementation
//
void B::serialize() {
A::serialize();

// Serialize own stuff
}



-Markus-

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement