Class fails to override base class function.

I am trying to develop a mod library which compiles up against a static library that contains class "Enemy". I then tried making a link to the static library and made class "ScaryBoi".

Enemy.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #pragma once
#include <string>
#include <iostream>
class Enemy
{
public:
	Enemy();
	~Enemy();
	//test mod library
	virtual void sayHy() {
		std::cout << "Hy" << std::endl;
	};

	std::string getName() const { return name; }

protected:
	std::string name;
};



Enemy.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "Enemy.h"



Enemy::Enemy()
{
}


Enemy::~Enemy()
{
}


ScaryBoi.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma once
#include <Enemy.h>
#include <iostream>
class ScaryBoi : public Enemy
{
public:
	ScaryBoi();
	~ScaryBoi();
	
	virtual void sayHy() override {
		std::cout << "Hello there" << std::endl;
	};
};


ScaryBoi.cpp
1
2
3
4
5
6
7
8
9
10
11
12
include "ScaryBoi.h"


ScaryBoi::ScaryBoi()
{
	name = "Ghost";
}


ScaryBoi::~ScaryBoi()
{
}


I then made a vector of class "Enemy" and ran sayHy() from each. One of the elements was of type ScaryBoi. For some reason, it always says "Hy" and not "Hello There".

Basically, why won't it run the function of the inherited class?
Your array is an array of Enemy objects. When you're trying to add an element of type ScaryBoi, what you're really doing is crating an element of type Enemy - because that's what your vector is - and setting its values to be a copy of the Enemy parts of your ScaryBoi object. It's the equivalent of doing:

1
2
3
4
ScaryBoi my_object;
Enemy vector_element = my_object;

vector_element.sayHy();  // This is an Enemy, so prints "Hy". 


This is called object slicing.

If you want to use polymorphism, you need to use pointers to the base class, rather than base class objects:

1
2
3
4
5
ScaryBoi my_object;
Enemy* vector_element = &my_object;

vector_element->sayHy();  // Polymorphism allows this to be treated as a ScaryBoi, so prints "Hello there". 


Last edited on
Thanks that worked.
You're welcome - glad I could help.
Topic archived. No new replies allowed.