C++: the private parameter be changed after another class be initialized

June Lin 41 Reputation points
2022-03-18T09:41:42.977+00:00
class baseClass
{
public:
baseClass() {};
~baseClass();

virtual void Name(char* value)
{
value = (char *)"hello base class";
}

};

class overrideClass : public baseClass
{
private:
char* _name;

public:
overrideClass(char *name)
{
_name = name;
}
~overrideClass();

void Name(char *value)  override
{
value = _name;
}

};

class controlClass
{
private:
std::vector<baseClass*> baseCollected;
public:
controlClass()
{
overrideClass *override0 = new overrideClass((char*)"first");
overrideClass *override1 = new overrideClass((char*)"second");
baseCollected.push_back(override0);
baseCollected.push_back(override1);
}
~controlClass() {};
std::vector<baseClass*> GetBaseClassList()
{
return baseCollected;
}

};

It is a simple structure of my idea. When I initialize the second overrideClass and assign "name". It always changes the first parameter of "name".
Does the idea really cannot work?

Developer technologies | C++
{count} votes

2 answers

Sort by: Most helpful
  1. Petrus 【KIM】 546 Reputation points
    2022-03-25T07:05:19.197+00:00

    You need Pointer-Pointer...

    Change the Name functions To...

    virtual void Name(char** value) 
    {
       *value = (char*)"hello base class";
    }
    
    void Name(char** value) override
    {
       *value = _name;
    }
    

    then test, like this

    controlClass oControlClass;
    char * psz = 0x00;
    
    oControlClass.GetBaseClassList()[0]->Name((char**)&psz);
    printf(psz);
    oControlClass.GetBaseClassList()[1]->Name((char**)&psz);
    printf(psz);
    
    1 person found this answer helpful.
    0 comments No comments

  2. Guido Franzke 2,191 Reputation points
    2022-03-18T10:34:15.407+00:00

    Hello,
    do not use char* as long as you don't use a char array for your string. And do not cast the string "hello" to char*. "hello" is always const char*.
    To make it easy for you, use std::string name instead of char* name. char* is only a pointer to a character (or character string), but it is not a string as you want to use it!
    When you use char* as a string, you must use a char array, e.g. char name[100]. And then use the C-routines for character strings like strcpy, strcat, etc.
    Read this:
    std::string
    c_strings.htm
    what-is-the-difference-between-char-s-and-char-s

    Regards, Guido

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.