用基类指针创建的派生类对象,无法访问派生类对象的数据和成员

时间:2022-11-09 20:00:30
class A{};
class B:public A{
public:
  void f();
  int a;
}
int main()
{
A * p=new B();
}

//用p无法访问B类的数据和成员函数,那么这个新建的对象存不存在f()和a?
 
这个新对象的储存结构仍是类B,但是p是基类对象所以没办法访问f()和a,
所以需要加virtual让f成为虚函数,或者dynamic_cast类型转向子类,
又或者((B*)p)->f(),((B*)p)->a
 
class CObject
{
	public:
		virtual int cleanup() = 0;
		virtual void setid(int id)=0;
		virtual int getid()=0;
		virtual int getSize() = 0;
};

class CCharacter:public CObject
{
public:
	CCharacter():m_nSize(10){}
	 int cleanup(){ return 0;}
	 void setid(int id){  m_id = id;}
	 int getid(){ return m_id;}
	 int getSize(){ return m_nSize;}
private:
	int m_id;
public:
	int m_nSize;
};
int main()
{
	CObject *pObject = new CCharacter;
	pObject->setid(123);
	printf("MSG:id = %d\n",pObject->getid());
	cout<<pObject->getSize()<<endl;
	system("pause");
	return 0;
}