Accessing derived class data members

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prashanth Kumar B R
    New Member
    • Jun 2007
    • 5

    Accessing derived class data members

    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_Stri ng element_text) ;
    }
    class Derived: pubilc Base
    {
    pubilc:
    int ele;
    bool decode(AOC_Stri ng 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
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    Originally posted by Prashanth Kumar B R
    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_Stri ng element_text) ;
    }
    class Derived: pubilc Base
    {
    pubilc:
    int ele;
    bool decode(AOC_Stri ng 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.

    Comment

    • Prashanth Kumar B R
      New Member
      • Jun 2007
      • 5

      #3
      Originally posted by zodilla58
      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?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by Prashanth Kumar B R
        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:

        [code=cpp]
        Base *Ptr = new Derived;

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

        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.

        Comment

        Working...