Polymorphism program questions

Pages: 12
Ok so i was watching this video on polymorphism and it was way better than the others, i kind of understand stuff better but there are some things im confused on what they are:


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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
using namespace std;

class Weapon
{
    private:
        int attack;
        string name;

    public:
        Weapon(const string & n, int a): name(n), attack(a)
        {

        }
        const string & get_name()
        {
            return name;
        }
        int get_attack()
        {
            return attack;
        }
};


class Sword: public Weapon
{
    private:
        int sharpness;
    public:
        Sword(const string & n, int a, int s): Weapon(n,a), sharpness(s)
        {

        }
};

class MagicAttack: public Weapon
{
    private:
        int MpCost;
    public:
        MagicAttack(const string & n, int a, int mpc): Weapon(n,a), MpCost(mpc)
        {}
};

int main()
{
    Weapon* wsword = new Sword("Red Sword", 15, 5);
    Weapon* wmagic = new MagicAttack("Lightning", 45, 200);

    Weapon* weapons[2] = {wsword, wmagic};

    for(int i = 0; i <2; i++)
    {
        cout << weapons[i]->get_name() << ": " << weapons[i]->get_attack() << endl;
    }

    delete wsword;
    delete wmagic;
}


What is const and new

why did he do this : name(n), attack(a) after weapon
and :public Weapon after the other classes, i think i might understand that, it so he can use the vars in Weapon in the child classes? also what is
string & n doing, why is he referencing n? i think i know why but tell me just in case.

he also said that you need to delete wsword and wsmagic but didnt really say why i dont think. Other than that i pretty much understand everything else. well there are a few more things but lets just start with this for now. I would google this stuff but i always get technical answers, and for me to understand it i need it explained in lamens terms, a very un technical explanation will help me understand this stuff. thanks in advanced.
closed account (o3hC5Di1)
const in the context of your code means a constant variable.
These are variables of which the value cannot be changed:
http://cplusplus.com/doc/tutorial/constants/

New is a keyword to allocate memory dynamically, whenever yo u do you need to free the memory or it may cause the program to become vulnerable or unstable:
http://cplusplus.com/doc/tutorial/dynamic/

Variables are passed to functions by reference so that the function can directly edit the variable, isntead of working on a copy of it:
http://cplusplus.com/doc/tutorial/functions2/

For more on polymorphism and inheritance:
http://cplusplus.com/doc/tutorial/inheritance/
http://cplusplus.com/doc/tutorial/polymorphism/


Hope that helps.
Let us know if you have any further questions.

All the best,
NwN
I'd suggest reading the documentation at this website. Take a look at inheritance and dynamic memory allocation.
Last edited on
Im having a little bit of trouble with my new program. I cant seem to figure it out.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Enemy
{
    private:
        int Ehealth;
        int Elevel;
        string Ename;
    public:
        Enemy(const string& n, int eh, int el):
        Ename(n), Ehealth(eh), Elevel(el){}

        const string & get_name(){return Ename;}
        int get_level(){return Elevel;}
        int get_health(){return Ehealth;}
};

class Stats
{
    private:
        int health;
        int xp;
        int money;
        string name;
    public:
        Stats(const string& n, int x, int h, int m):
        name(n), health(h), xp(x), money(m){}

        const string & get_pname(){return name;}
        int get_health(){return health;}
        int get_xp(){return xp;}
        int get_money(){return money;}
};

class Trex: public Enemy
{
    private:
        int stomp;
        int bite;
    public:
        Trex(const string& n, int eh, int el, int a1, int a2):
        Enemy(n, eh, el), stomp(a1), bite(a2){}
};

class Player: public Stats
{
    public:
        Player(string& n, int x, int h, int m):
        Stats(n, x, h, m){}
};

int main()
{
    Enemy* Etrex = new Trex("T-Rex", 100, 1, 25, 34);
    Stats* Pstats = new Player("Player1", 0, 100, 0);

    cout << Trex << endl;

    delete Etrex;
    delete Pstats;
}


I got these errors but i cant figure out what i need to fix.


C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp||In constructor 'Enemy::Enemy(const std::string&, int, int)':|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|12|warning: 'Enemy::Ename' will be initialized after|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|10|warning: 'int Enemy::Ehealth'|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|14|warning: when initialized here|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp||In constructor 'Stats::Stats(const std::string&, int, int, int)':|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|28|warning: 'Stats::name' will be initialized after|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|25|warning: 'int Stats::health'|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|30|warning: when initialized here|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp||In function 'int main()':|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|59|error: no matching function for call to 'Player::Player(const char [8], int, int, int)'|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|52|note: candidates are: Player::Player(std::string&, int, int, int)|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|50|note: Player::Player(const Player&)|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|61|error: expected primary-expression before '<<' token|
C:\Users\Chay Hawk\Desktop\Battle Arena\main.cpp|59|warning: unused variable 'Pstats'|
||=== Build finished: 2 errors, 7 warnings ===|
You have two warnings about the order of initialization of your constructors. You can ignore these, since the initializations have no side effects.

There are also two errors.

1) At line 52,
error: no matching function for call to 'Player::Player(const char [8], int, int, int)

You need to delcare the Player constructor as:
Player( const string& n, int x, int h, int m):.
The compiler is trying to tell you it can't convert "Player1" from const char * to a non-const string.

2) At line 61:
expected primary-expression before '<<' token

You can't output a type name. You have to output an instance. In this case you need:
cout << *Etrex << endl;


Ah i see, the first was just my overlooking, but the second still wont let me output, i tried just Etrex and it gave me a hex number.
bump
You have to specify the * in front of Etrex, otherwise you will just get the value of the pointer. However, Enemy needs to overload the << operator for you to be able to output an instance of Enemy.
I did that an d nothing, what do you mean by operator overloading? can you give me a small example ?
closed account (o3hC5Di1)
Ch1156 - again, if your questions are not related to the original subject of the thread, it's best to create a new thread.

As to your question on operator overloading:

You are trying to do the following:

cout << Trex << endl;

The compiler does not know how to print out custom datatypes (classes) unless you tell it.
So by overloading the << opearator, we tell the compiler how it should handle printing a Trex object.

Using your code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Trex: public Enemy
{
    private:
        int stomp;
        int bite;
    public:
        Trex(const string& n, int eh, int el, int a1, int a2):
        Enemy(n, eh, el), stomp(a1), bite(a2){}  //by the way, a1 and a2 are not passed to this function
        friend std::ostream& operator<<(std::ostream& os, Trex& tr);
};

std::ostream& operator<<(std::ostream& os, Trex& tr)
{
    os << "Stomp power: " << tr.stomp << "\nBite Power: " << tr.bite;
    return os;
}


Now you can do cout << Trex << endl; and it will print out its properties.

Hope that helps.

All the best,
NwN
Sorry, its just that i have a tendancy to flood forums so i just keep to one thread. but anyways please explain what you did

friend std::ostream& operator<<(std::ostream& os, Trex& tr);

1
2
3
4
5
std::ostream& operator<<(std::ostream& os, Trex& tr)
{
    os << "Stomp power: " << tr.stomp << "\nBite Power: " << tr.bite;
    return os;
}


I read up a little on operator it said you could define your own operators or something? but please explain everything else
Please take a look at the documentation. It explains operator overloading. Anyway, what were you trying to do here cout << *Etrex << endl;?

If you are trying to output stomp or bite value, you can do it without operator overloading. As these variables are private, you cannot access them directly from outside the class, so you need to have a getter function, something like this:-

1
2
3
4
int getStomp()
{
    return stomp;
}


Note that this function must be public.
closed account (o3hC5Di1)
Hi there,

@Dash - see this thread: http://cplusplus.com/forum/beginner/77885/ .

The line friend std::ostream& operator<<(std::ostream& os, Trex& tr); in the class definition tells the class "this function is allowed to access your private data". We need that in order to print the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//operator<<()  iss the way to overload an operator
//ostream& is it's return type, don't worry about this too much right now
//(std::ostream& os, Trex& tr) on the left side of << there is an ostream (like std::cout), on the right side there is your Trex
//ie: std::cout << Trex;  (stream << trex object)
std::ostream& operator<<(std::ostream& os, Trex& tr)
{
    //the stream here is called os instead of cout, but works the same
    //notice how we can access tr.stomp - this is because this functionis a friend of the trex class
    os << "Stomp power: " << tr.stomp << "\nBite Power: " << tr.bite;

    //return the stream, this makes you able to chain the operators
    //ie: std::cout << trex1 << std::endl << trex2; 
    return os;
}


Hope that clears it up for you.

You can also overload the other operators, such as +,-,*,/, =, [], etc.
Worth looking into at some point.

All the best,
NwN
Last edited on
Ok i see, now is there anything wrong with my code so far? or anything that can be fixed or improved? NwN said in a previous post: Enemy(n, eh, el), stomp(a1), bite(a2){} //by the way, a1 and a2 are not passed to this function why arent they and is it important? i tried deleting them but got errors so they must be.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Enemy
{
    private:
        int Ehealth;
        int Elevel;
        string Ename;
    public:
        Enemy(const string& n, int eh, int el):
        Ename(n), Ehealth(eh), Elevel(el){}

        const string & get_name(){return Ename;}
        int get_level(){return Elevel;}
        int get_health(){return Ehealth;}
};

class Stats
{
    private:
        int health;
        int xp;
        int money;
        string name;
    public:
        Stats(const string& n, int x, int h, int m):
        name(n), health(h), xp(x), money(m){}

        const string & get_pname(){return name;}
        int get_health(){return health;}
        int get_xp(){return xp;}
        int get_money(){return money;}
};

class Trex: public Enemy
{
    private:
        int stomp;
        int bite;
    public:
        Trex(const string& n, int eh, int el, int a1, int a2):
        Enemy(n, eh, el), stomp(a1), bite(a2){}
};

class Player: public Stats
{
    public:
        Player(const string& n, int x, int h, int m):
        Stats(n, x, h, m){}
};

int main()
{
    Enemy* Etrex = new Trex("T-Rex", 100, 1, 25, 34);
    Stats* Pstats = new Player("Player1", 0, 100, 0);

    cout << Trex << endl;

    delete Etrex;
    delete Pstats;
}


Im going to try to go read up on some stuff like you guys suggested but concentration isnt my strong suit but i'll try. If i have any questions i'll be back. BTW based on all the problems i have been having with stuff can you give me links to documentation that you think would help me understand this better? I was given links in previous posts and i'll read those now but anything else?
Last edited on
@Nwn Getters are not bad, unneeded getters are bad. Anyway, I was showing the OP how to output value, I did not want to change the access level.

Here is the link:-
http://cplusplus.com/doc/
Last edited on
closed account (o3hC5Di1)
As for documentation, books are probably the best thing to do.
Check out this list: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
Some of the material mentioned there is available online (legitimately).

As to this line in the Trex class:

Enemy(n, eh, el), stomp(a1), bite(a2){}

It doesn't even belong there.
A constructor for Enemy should go in the Enemy class, not the Trex class.

Other than that, your function takes n, eh and el as arguments - so where do a1 and a2 come from?
The program won't be able to find those values, I would even find it odd if this code actually compiles like this.
Just leave that line out - you're not using it and you won't ever need it.

Hope that helps,

All the best,
NwN
I watched this video, this is how i learned to do all this polymorphism stuff. Maybe it would make sense if you saw it but idk i just followed him:

http://www.youtube.com/watch?v=gEAZob_mMRk&feature=plcp
Last edited on
Following a video tutorial doesn't mean you understand the concepts. Not trying to insult you but I don't think you should be messing with inheritance and polymorphism until you have a firm grasp of classes. Polymorphism also requires a good understanding of pointers which I dont believe you have.
I understand the concept of pointers its just a bit confusing writing it all out. Im watching more tutorials and i think i know how to do it now. Im just going to keep practicing until i get better with them. then move on to classes.
While video tutorials are easy, I think you should get a book. I'd recommend C++ Primer.
Pages: 12