I have two classes in C++, where one inherits from the other:
class A {
public:
virtual void Initialize(){
m_MyString = "Default value";
}
protected:
string m_MyString;
}
class B : public A {
public:
void Initialize(){
A::Initialize();
m_MyString = "New Value";
}
}
Is there a difference between the above class B and this one?
class B : public A {
public:
void Initialize(){
A::Initialize();
A::m_MyString = "New Value";
}
}
It seem using the scoping operator will result in a the string having garbage, correct? I'm thinking when it overrides, the A::m_MyString is different than B::m_MyString. Does this even make sense?
I'm seeing the variable get set in A, then when we return to B, have garbage. This has to do with "hidden" vs. overridden?
Your code is not valid in many ways. It should look like:
class A { // << errors were here
public:
virtual void Initialize(){
m_MyString = "Default value";
}
protected:
string m_MyString;
}; // << lost ;
class B : public A // << errors were here
{
public:
virtual void Initialize(){ // << virtual
A::Initialize(); // has no effect in the end
A::m_MyString = "New Value"; // same as `m_MyString = "New Value";`
}
}; // << lost ;
In the code above there is no difference with m_MyString. Post your actual code with error.
If your code looks like:
class B : public A
{
public:
virtual void Initialize(){
// here is a difference
A::m_MyString = "New Value";
m_MyString = "New Value";
}
protected:
string m_MyString; // !!! overridden
};
Then there is a difference because B has two instances of m_MyString: A::m_MyString and B::m_MyString.
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