简体   繁体   中英

Dynamic linking in C++ not working

I have a problem with a small program. I hope you can open my eyes.

I have one class, "User", with "name" as a class member and a "toString()" method:

class User
{
protected:
        string name;
public:
        User(){}
        User(string name) { this->name = name; }
        virtual string toString() const { return name; }
};

I have another class, "Employee" that extends User, and it also includes an "id" and overloads "toString()" method:

class Employee : public User
{
private:
        string id;
public:
        Employee(string name, string id) : User(name) { this->id = id;}
        string toString() const { return "("+id+")"+name; }
};

Well, now I have another class, "Stack" with an array of users (of User objects, not User pointers):

class Stack
{
private:
        User *stack;
        int sp;
        int size;
public:
        Stack(int size){this->size = size; stack = new User[size]; sp = 0;}

.
.
.

The problem is this:

Stack s(10);
Employee e1("pepito", "1234");

cout << e1.toString(); // PRINTS (1234)pepito -> ITS OK

s.push(e1);
cout << s.pop().toString(); // PRINTS pepito -> WRONG (it uses the toString method of the super class).

I think, I could be getting this result because of:

  • Storing objects instead of pointers or references to objects.
  • In the line: stack = new User[size], it calls the default constructor of User (that I had to write explicitly, and I don't know if that was right).

I think, I could be getting this result because of:

  • Storing objects instead of pointers or references to objects.

Correct. You are dynamically allocating an array of User s. The objects in this array can only be User s and nothing else. They are never Employee s. To get polymorphic behaviour in C++, you need to use pointers or references to User .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM