I was trying to write an interface for a variable value. The base class only provides an enum field, where the type of the Variable is stored (like int, char, etc...) and some virtual functions.
The classes inheriting this interface should implement a representation of a variable type each.
#include <iostream>
enum Type
{
INT, CHAR
};
class Var
{
Type type;
public:
Var(Type t):
type(t)
{}
virtual void printValue()
{
std::cout << "-\n";
}
virtual void printType()
{
std::cout << type << std::endl;
}
};
class IntVar : public Var
{
int value;
public:
IntVar(int i):
Var(INT),
value(i)
{}
void printValue()
{
std::cout << value << std::endl;
}
};
class CharVar : public Var
{
char value;
public:
CharVar(char c):
Var(CHAR),
value(c)
{}
void printValue()
{
std::cout << value << std::endl;
}
};
Then I tried this:
Var* np = new IntVar(1);
np->printType();
np->printValue();
np = new CharVar('a');
np->printType();
np->printValue();
The output was
0 (Type::INT), 1, 1 (Type::CHAR), a
so everything worked as expected, but when I tried the same with references, the outcome was a bit strange.
Var& nr = *(new IntVar(1));
nr.printType();
nr.printValue();
nr = *(new CharVar('a'));
nr.printType();
nr.printValue();
Here the output was
0 (Type::INT), 1, 1 (Type::CHAR) and 1
Why did the code work, when using pointers and didn't work with references? Or do I overlook some obvious errors?
The solution using pointers makes nr point to an IntVar at first, and then to a CharVar.
The solution using references creates an IntVar object, then it creates a new name (nr) for that object and then changes the values of this object based on the values of a CharVar.
References cannot be rebased as you did with pointers. A reference references the same object throughout its lifetime.
The statement
nr = *(new CharVar('a'));
is an assignment with a very different meaning than
np = new CharVar('a');
Section 12.8:
The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition....
nr is using the implicit assignment operator Var::operator=() that copies fields from Var. You are not changing the reference type, it is still a reference to an IntVar object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With