By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,985 Members | 1,776 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,985 IT Pros & Developers. It's quick & easy.

Accessing derived class data members

P: 5
How can i access a public data member of a derived class with a pointer to the base class.

class Base
{
public:
Base(){};
virtual ~Base(){};
virtual bool decode(AOC_String element_text) ;
}
class Derived: pubilc Base
{
pubilc:
int ele;
bool decode(AOC_String element_text)
{
}
}

Base *Ptr = (Base *)new(Derived);

Ptr->decode("123"); //works fine
Ptr->ele; //this throws an error... why is this wrong, what's the right way

Many Thanks
Jun 20 '07 #1
Share this Question
Share on Google+
3 Replies


Meetee
Expert Mod 100+
P: 931
How can i access a public data member of a derived class with a pointer to the base class.

class Base
{
public:
Base(){};
virtual ~Base(){};
virtual bool decode(AOC_String element_text) ;
}
class Derived: pubilc Base
{
pubilc:
int ele;
bool decode(AOC_String element_text)
{
}
}

Base *Ptr = (Base *)new(Derived);

Ptr->decode("123"); //works fine
Ptr->ele; //this throws an error... why is this wrong, what's the right way

Many Thanks
Pointer *Ptr is a base pointer, and decode is a virtual method. So base pointer can access this method and not ele.
Jun 20 '07 #2

P: 5
Pointer *Ptr is a base pointer, and decode is a virtual method. So base pointer can access this method and not ele.
Is there any way by which i can access the Element of the derived class from *Ptr?
Jun 20 '07 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
Base *Ptr = (Base *)new(Derived);

Ptr->decode("123"); //works fine
Ptr->ele; //this throws an error... why is this wrong, what's the right way
Stop casting. The code should be:

Expand|Select|Wrap|Line Numbers
  1. Base *Ptr = new Derived;
  2.  
  3. Ptr->decode("123"); //works fine
  4. Ptr->ele; //this throws an error... why is this wrong, what's the right way
  5.  
Ptr is a Base* so it can access only Base members.

If you need to use Ptr to access ele, then you need to design your classes to support the Visitor design pattern.
Jun 20 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.