Update class data from struct

Feb 27, 2014 at 1:26am
Hello, I'm trying to learn c++ and came across a doubt (one of many, but yeah...).

It's about the usage of struct...

Ok, so this is the general idea of what I tried:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Human
{
    string name;
    int age;
};

class People
{
    string name;
    int age;

public:
    void update_data(struct x)
    {
        this->name = x.name;
        this->age = x.age;
    }
};

(Then, of course, I'd create an object from the struct and one from the class, etc...

Now, there may be other issues, I don't know, but my main point here is that I'd want to update the variables on a class based on the variables of a struct, the "update_data" function in my example, that's my main question.
By now. of course, I've realized it doesn't work like that because well... it didn't work, but is there any (simple, if possible) way to do that?

Some details, like this one, I just can't seem to find over the internet.

Thank you for your attention.
Feb 27, 2014 at 6:01am
YOu should look into inheritance.
for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>

struct Entity
{
    std::string name;
    int age;
    void update_data(Entity& rhs)
    {
        name = rhs.name;
        age = rhs.age;
    }
};

struct Human: Entity
{
};

struct People: Entity
{
};

int main()
{
    Human h;
    h.name = "Max";
    h.age = 24;

    People p;
    p.update_data(h);
    std::cout << p.name;
}
http://ideone.com/JYNIiy
Topic archived. No new replies allowed.