Error accessing Control++ objects via base shared_ptrs

Discussions about product bugs & problems!
Note: This is no replacement for the Official ETM Support!
3 posts • Page 1 of 1
fleitner
Posts:15
Joined: Thu May 11, 2017 10:04 am

Error accessing Control++ objects via base shared_ptrs

Post by fleitner »

Hi there,

I just noticed some weird behavior while playing with classes. Consider the following code

Code: Select all

class Base
{
  public Base() { DebugN("Base"); i = 1; }
  public string values() { return ("Base::i = " + i); }
  protected int i;
};

class Derived : Base { 
  public Derived() { DebugN("Derived"); i = 2; j = 22; }
  public string values() { return ("Derived::i = " + i + ", j = " + j); }
  private int j;
};

main()
{
  shared_ptr p = new Base();
  DebugN(p.values());
  DebugN("------------------------------------------------------");
  
  p = nullptr;
  p = new Derived();
  DebugN(p.values());
}

The line p = nullptr; should not have any effect. Assigning an object to p the line after should completely remove any previous content that it pointed to.
Surprisingly the behavior changes depending on the existence of that line..

With the line included, it will output the following, expected, log output:
WCCOAui1:["Base"]
WCCOAui1:["Base::i = 1"]
WCCOAui1:["------------------------------------------------------"]
WCCOAui1:["Base"]
WCCOAui1:["Derived"]
WCCOAui1:["Derived::i = 2, j = 22"]
However, removing that line results in the following and rather unexpected log:
WCCOAui1:["Base"]
WCCOAui1:["Base::i = 1"]
WCCOAui1:["------------------------------------------------------"]
WCCOAui1:["Base"]
WCCOAui1:["Derived"]
WCCOAui1:["Base::i = 2"]
As you can see it runs through the Derived constructor and assigns the value to i, but it calls the base values() method instead of the derived version.


Best regrads
Frank

mkoller
Posts:741
Joined: Fri Sep 17, 2010 9:03 am

Re: Error accessing Control++ objects via base shared_ptrs

Post by mkoller »

"The line p = nullptr; should not have any effect."

Wrong.
By definition CTRL does auto-dereferencing.
When p already points at some class instance and you assign another to it, then effectively the pointed-at object is the target of the assignment, not the pointer itself.

If you want to explicitely assign a new pointer to p, then either assign a nullptr before or use the function assignPtr()

fleitner
Posts:15
Joined: Thu May 11, 2017 10:04 am

Re: Error accessing Control++ objects via base shared_ptrs

Post by fleitner »

Hi Martin,

thank you for the answer and your explanation. It makes sense to me now.
Coming from C++ I completely misinterpreted what the code is supposed to do and thus was very surprised by the result.

Best regards
Frank

3 posts • Page 1 of 1