简体   繁体   中英

How to pass “&player” object into another inherited class constructor (“score”)?

I am new to C++ and I am creating a small program to understand more about inheritance in programming languages.

From what I gather, inheritance is when you have the authority and permission to obtain all member functions and values of the parent/base class. An analogy in real life would be inheriting some of my father's physical properties like eye colour etc (although I wish I could inherit his business mind...)

Anyways, one thing I am trying to do is to try and pass an already initialized object into an inherited class constructor.

This is my code so far:

#include <string>
#include <iostream>
using namespace std;

class player{
private:
    string name;
    int level;

public:
    player(const string &n, const int &l) : name(n), level(l){};

    string getName() const {return name;}
    int getLevel() const {return level;}
};

class score: public player{
private:
    int scores;

public:
    score(const int &s, const string &n, const int &l) : player(n, l), scores(s){};
    void setScore(int newScores){scores = newScores;}
    int getScore() const {return scores;}
};

int main(){
    player steve("steve", 69);
    cout << steve.getName() << endl;
    cout << steve.getLevel() << endl;
}

Basically, I want to pass the object that I have intialised in my main() program function steve by reference into a constructor in the score class. However, I don't know how to do this? Would it be something like score(const player &p, const int &s) : player(&p), scores(s) ?? I get how to pass like member values, but I am interested in passing in objects themselves?

Would mean a lot if someone could assist me here, as I really like programming especially C++

You can't extend an object of a base class ( player ) to an object of a child class ( score ) because this would require to allocate more memory space directly after the original object to store the additional elements of the child class.

In your example, you can define this constructor to copy values from the player object for a new score object:

score(const player &p, const int &s) : player(p.n, p.l), scores(s){};

If you just want to link the player object, then the score class must include a pointer to this object.

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