I am seeing this unexpected output value with the following code while using a base class's reference as a variable inside another class. Can someone please help me to understand this?
#include <iostream>
class base {
public:
explicit base(int val) : myVar(val) {
std::cout << "base class constructor" << std::endl;
}
~base() {
std::cout << "base class destructor" << std::endl;
}
int getVal() { return myVar;}
private:
int &myVar;
};
class someClass {
public:
base &helloBase;
someClass(base &obj) : helloBase(obj) {
std::cout << "someClass constructor. "
<< "value is : "
<< helloBase.getVal()
<< std::endl;
}
someClass(const someClass&) = delete;
someClass(const someClass&&) = delete;
someClass& operator=(someClass const &) = delete;
someClass& operator=(someClass const &&) = delete;
~someClass() {
std::cout << "someClass destructor" << std::endl;
}
};
int main() {
base newBase(10);
std::cout << "Hello trial from base : " << newBase.getVal() << std::endl;
someClass newSome(newBase);
std::cout << "Hello trial from base again after new class obj creation : " << newBase.getVal() << std::endl;
std::cout << "Hello trial from new class : " << newSome.helloBase.getVal() << std::endl;
return 0;
}
and the output is as follows
base class constructor
Hello trial from base : 10
someClass constructor. value is : 32767
Hello trial from base again after new class obj creation : 32767
Hello trial from new class : 32767
someClass destructor
base class destructor