Author Topic: How can I access the Derived class member by a Base class pointer  (Read 899 times)

administrator

  • Administrator
  • Full Member
  • *****
  • Posts: 69
How can I access the Derived class member by a Base class pointer?
Do I need to do a type-casting or any other way?



No way to access directly since data members can not virtual. You need to cast it back to derived class. With derived class pointer only you can derived class data members. Alternatively you can have virtual function that does the work for you. Refer to the source code below:


#include <iostream>

class mybase
{
public:

   virtual void changedata(int a) = 0;

};

class myderived : public mybase
{
public:
   int m;
   virtual void changedata(int a) { m = a; }

};


void main()
{
   mybase *p = new myderived();
   p->changedata(12);
   
   myderived *d = (myderived*) (p);
   std::cout << d->m;
}

« Last Edit: November 01, 2011, 03:31:44 pm by administrator »

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1