Cherno c++ learning -- inheritance and virtual function

Cherno视频:https://www.youtube.com/watch?v=oIV2KchSyGQ&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=28 

子类包含了父类所有的public,protected属性:

#include<iostream>

class Entity {
public:
	float X, Y;
	void Move(int ax, int ay) {
		X += ax;
		Y += ay;

	}
};

class Player :Entity
{
public:
	char * name;

	char * GetName()const {
		return name;
	}
};



int main() {
	std::cout << "sizeof(Entity): "<<sizeof(Entity) << std::endl;
	std::cout << "sizeof(Player): "<<sizeof(Player) << std::endl;

	std::cin.get();
}

 

 

virtual function 

dynamic dispatch --->compile is typically implemented by our V table

a V table is a table which contains a mapping for all the virtual functions inside out base class

so that we can map them to the correct overwritten function at runtime


class Entity {
public:
	virtual std::string GetName() const {//virtual -->tell compiler to  generate a V table for this function
		return "Entity";             //so that if it is overwritten youcan point to the correct function with this table
	}
};

class Player : public Entity
{
public:
	Player(const std::string& name):
		m_name(name){}
	std::string  m_name;

	std::string  GetName()  const override{
		return m_name;
	}
};
void PrintName(Entity* entity) {
	std::cout << entity->GetName() << std::endl;
}
int main() {
	
	Entity* e = new Entity();
	PrintName(e);
	Player* p = new Player("Cherno");
	PrintName(p);

	std::cin.get();
}

注意:

virtual function has two runtime costs:

1.have additional memery to store V table,

includes a member pointer in the actual base class that points to the V table (基类中含有一个指向V-table的指针)

2. when we call a virtual function we have to go through V table to determine which function to actually map to(每次调用虚函时,都需要在V-table中查找)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值