virtual property c++ code example
Example 1: virtual function in c++
#include <iostream>
#include<string>
class Entity {
public:
virtual std::string GetName() { return "Entity"; }
void Print() { std::cout << "This is Base class" << std::endl;}
};
class Player :public Entity {
std::string m_name;
public:
Player(const std::string& name)
:m_name(name)
{};
void Print() { std::cout << "This is Sub class" << std::endl; };
std::string GetName()override { return m_name; };
};
int main()
{
Entity* e = new Entity();
std::cout << e->GetName() << std::endl;
Player* p = new Player("Jacob");
std::cout << p->GetName() << std::endl;
PrintName(p);
Entity* notvirtualentity = new Entity();
Player* notvirtualpalyer = new Player("XX");
notvirtualentity = notvirtualpalyer;
notvirtualentity->Print();
std::cin.get();
}
Example 2: C++ pointer to base class
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
class Parent {
public:
virtual void sayHi()
{
std::cout << "Parent here!" << std::endl;
}
};
class Child : public Parent {
public:
void sayHi()
{
std::cout << "Child here!" << std::endl;
}
};
class DifferentChild : public Parent {
public:
void sayHi()
{
std::cout << "DifferentChild here!" << std::endl;
}
};
int main()
{
std::vector<Parent*> parents;
srand(time(NULL));
for (int i = 0; i < 10; ++i) {
int child = rand() % 2;
if (child)
parents.push_back(new Child);
else
parents.push_back(new DifferentChild);
}
for (const auto& child : parents) {
child->sayHi();
}
return 0;
}
Example 3: virtual function c++
#include <iostream>
#include <string>
class Entity {
public:
virtual std::string getName();
void print();
};
virtual std::string Entity::getName() {
return "Entity";
}
void Entity::print() {
std::cout << "This is the base class" << std::endl;
}
class Player : public Entity {
std::string m_name;
public:
Player(const std::string& name): m_name(name) {};
void print();
virtual std::string getName();
};
virtual std::string Player::getName() {
return m_name;
}
void Player::print() {
std::cout << "This is the sub class" << std::endl;
}
int main() {
Entity* e = new Entity();
std::cout << e->getName() << std::endl;
Player* p = new Player("Jacob");
std::cout << p->getName() << std::endl;
p->print();
e->print();
Entity* notVirtualEntity = new Entity();
Player* notVirtualPlayer = new Player("Bob");
notVirtualEntity = notVirtualPlayer;
notVirtualEntity->print();
notVirtualEntity->getName();
}