Container of Inherited Class Instances

Hello everyone, I've been working a couple of days on this school project, here the issue I stepped into:
I have 3 classes that inherit some traits from an User parent class. The three sub-classes are meant to add some specific functions and attributes.
1
2
3
4
5
6
7
8
9
10
11
class User {
protected:
    string _username, _address;
    Date _date;
public:
    User();
    User(const User &to_copy);
    //Getters
    //Setters

};


1
2
3
4
5
6
7
8
9
class StandardUsr : public User {
private:
    string _name, _surname;
    char _gender;

public:
    //Getters
    //Setters
};

I then need to fit a bunch of instances of the three different sub-classes in some container (map), and to use them when needed. I instance a map<String,User> and fit them into it.
What happens is that the insertion "slices off" everything but the attributes/methods belonging to the parent User class.
I also tried to use User* pointers instead of User in the map, but when doing so, I can only use User's public methods.

What's the trick?
Last edited on
I also tried to use User* pointers instead of User in the map, but when doing so, I can only use User's public methods.


Whatever you do, you'll only be able to use User's public methods. That's the whole point of having a public interface, and a private implementation!

The trick is to properly design your class's interface, so that the class provides the services you want it to provide.

(And to use pointers in the container, so that polymorphism works properly.)
Last edited on
@MikeyBoy's hint about polymorphism should lead you to looking into virtual functions.
Sorry, I wasn't clear enough.I know i can only access public. What I mean is I cannot use methods of StandardUsr, but only User's. Even if I cast the pointer (User*) to (StandardUsr*), StandardUsr's data are not shown.
I'm now doing some edit, because I actually use pointers, dynamic memory, everything in a Template Class, and I'm quite a newbie actually.
I might have done some unwanted cast of some sort,I'll double check and be right back!
Thank you for now!
No unwanted casts.

Use virtual functions. That's exactly what they are there for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class Base
{
public:
   virtual void f() { std::cout << "Base" << std::endl; }
};

class Derived : public Base
{
public:
    Derived() : v(10) {}
    virtual void f() { std::cout << "Derived: " << v << std::endl; }
private:
    int v;
};

int main()
{
    Derived d;
    Base* bptr = &d;
    bptr->f();
}


We have a Base pointer, but it performs the Derived functionality because the function is virtual.
I did manage. Thank You!
Topic archived. No new replies allowed.