Cherno c++ learning -- inheritance and virtual function

本文深入探讨了C++中的类继承特性,通过具体代码示例解释了子类如何包含父类的所有public和protected属性。同时,文章详细介绍了虚函数的概念,包括Vtable的生成与使用,以及动态调度机制,展示了如何实现多态性和运行时函数覆盖。

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中查找)

import random general_questions = [ "What is the capital of France?", "How do I install Python on Windows?", "What is machine learning?", "What does HTTP stand for?", "How can I create a virtual environment in Python?" ] cpp_questions = [ "Explain inheritance in C++.", "What is the difference between stack and heap memory?", "How do you declare a constant variable in C++?", "What is a virtual function in C++?", "What is the purpose of the 'new' operator in C++?" ] answers = { general_questions[0]: "The capital of France is Paris.", general_questions[1]: "To install Python on Windows, download the installer from python.org and run it. Make sure to check the box that says 'Add Python to PATH' during installation.", general_questions[2]: "Machine learning is a subset of artificial intelligence that involves training algorithms to make predictions or decisions based on data.", general_questions[3]: "HTTP stands for HyperText Transfer Protocol, which is used for transmitting web pages over the internet.", general_questions[4]: "You can create a virtual environment using the command 'python -m venv env_name' followed by activating it with 'source env_name/bin/activate' on Unix or 'env_name\\Scripts\\activate' on Windows.", cpp_questions[0]: "Inheritance in C++ allows a class (called a derived or child class) to inherit properties and methods from another class (known as the base or parent class)[^2].", cpp_questions[1]: "Stack memory is automatically managed by the system, while heap memory requires manual allocation and deallocation using functions like malloc() or new. Stack is faster but limited in size, whereas heap is larger but slower to access.", cpp_questions[2]: "You can use the const keyword before the data type when declaring a variable, for example: const int value = 10;", cpp_questions[3]: "A virtual function is a member function in a base class that is expected to be redefined in derived classes. It enables dynamic dispatch through pointers or references to the base class.", cpp_questions[4]: "The 'new' operator is used to dynamically allocate memory on the heap for an object or array and returns a pointer to the allocated memory." } with open("cplus_faq_5000_pairs.txt", "w") as f: for i in range(5000): q_type = random.choice(["general", "cpp"]) if q_type == "general": question = random.choice(general_questions) else: question = random.choice(cpp_questions) answer = answers[question] f.write(f"{question}|{answer}\n")转话为c++
最新发布
07-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值