I have a class Child that inherits from a class Parent. They both have a private instance variable named a
. The parent class has a method to change the a
variable.
Parent.h
#pragma once
#include <iostream>
class Parent {
public:
Parent() {}
~Parent() {}
virtual void changeA() {
a++;
std::cout << "Parent a: " << a << std::endl;
}
private:
int a = 0;
};
Child.h
#pragma once
#include "Parent.h"
class Child : public Parent {
public:
Child() {}
~Child() {}
void changeA() {
Parent::changeA();
std::cout << "Child a: " << a << std::endl;
}
private:
int a = 0;
};
main.cpp
#include "Child.h"
#include "Parent.h"
#include <iostream>
int main() {
Parent parent = Parent();
Child child = Child();
parent.changeA();
std::cout << "---" << std::endl;
child.changeA();
return 0;
}
stdout
Parent a: 1
---
Parent a: 1
Child a: 0
It seems as if the Child object also has a copy of the Parent object. How do I get the Parent's changeA
method to change the Child's a
instance variable?
Clarification:
I need this because I have a parent class Entity
with two children Enemy
and Player
, and both classes need to use the same init
method inherited from Entity.