Correct use of this pointer

Pages: 12
I do have one issue though, I already defined all the stuff in character like name, race etc, so why do i need to keep re defining these things in the dragon and nord classes?


But you aren't redefining them, simply passing all the parameters to the constructors, so they can be constructed properly.

@JLBorges

Yes, we do go round and round, IMO it is one of the downfalls of this site, and one of the reasons that Stack Overflow is the way it is. However the good news is that we have experts such as yourself and others who are willing to help :+)
Last edited on
@Chay

You have created a new classes Dragon and Nord, but they have the same members as the class it inherits from. The Character objects have ability set to "None", but the Nord objects have a value. As it stands, this means that you shouldn't have inheritance here at all. Inheritance usually means that the derived class inherits the members from the base class and it has members that the base class does not, and these new members could be used to give the derived class it's different behaviour. At the moment all the classes have the same members but you just give them different values.

In fact you have duplicated the ability variable, so now there are 2 of them in the same object: Character::ability and Dragon::ability.

One can create different behaviour by having inherited functions doing different things for different types, like the speak function for example, or better a function that alters the state (changes values of member variables) differently depending on which function is called.
Last edited on
Thats what I was wondering about. Because as it stands I could probably just get away with the Character class and create the Nord and Dragon characters from that, but I want to understand inheritance so I wanted to try to create an example to keep in my notes to look at later.

And yes as JLBorges has said, this has been asked by me before a long time ago. Which is why I'm trying to create really quality examples of actual working functioning code and then keep it in a notebook that explains whats going on so I can go back and look at it and not have to keep asking over and over again. So the next time I take a 6 month break from programming I can just go back to my refresher notes and then get caught back up.

So to get this straight, my classes that inherit (Dragon and Nord) are not actually inheriting. So I should remove ability from Character or from the other two classes? All characters have abilities, but not all have Magicka. Im genuinely stumped as to how to structure the game information in the classes that will use inheritance in a useful way. I mean I want to have pre defined character classes like dragons and nords and all that in the game, so inheritance is the way to go here right?

I'm only using C++ for game development and nothing else so whatever solution is best for a game design approach would be ideal, if such a thing even exists. I mention that cause I know whatever approach you take is dependent on what you're trying to accomplish, so I just wanted to mention that i'm only learning for game development purposes.
Last edited on
@OP While the Characters all have the same attibutes and methods, like thay say, you don't need inheritance to remove the repetition. My advice to you is take the advice you've already been given, forget about YouTube andgo to learncpp or a similar website and do some study.

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//

#include <iostream>
#include <string>

class Gender
{
private:
    char m_gender;
public:
    Gender(char g = '?'){m_gender = g;}
    
    std::string display()
    {
        if(m_gender == 'F')
            return "FEMALE";
        else if(m_gender == 'M')
            return "MALE";
        else
            return "SOME OTHER GENDER";
    }
};


class Race: public Gender
{
private:
    std::string m_race_name;
public:
    Race(std::string name = "??"){ m_race_name = name; }
    std::string display(){return m_race_name;}
};


class Character: public Race
{
private:
    std::string m_name;
    Race m_race;
    Gender m_gender;
    
    double health{0};
    double magicka{0};
    double carryWeight{0};
    double stamina{0};
    
public:
    Character(std::string name, Race race, Gender gender)
    {m_name = name; m_race = race; m_gender = gender;}
    
    void display()
    { std::cout
        << "My name is " << m_name << ','
        << " I am from the " << m_race.display() << " race, and I am "
        << m_gender.display() << '\n';
    }
};

int main()
{
    // SETUP OBJECTS
    Gender male{'M'};
    Gender female{'F'};
    
    Race Dragon_1("Dragon");
    Race Dragon_2("other Dragon ");
    Race Nord("NORD");
    Race Claud("Claud team");
    
    Character ABC("Mirmulnir", Dragon_1, male);
    Character XYZ("Mirmulnir Again", Dragon_2, female);
    Character NNN("Lord Nord", Nord, female);
    Character CCC("Poor Claude", Nord, male);
    
    // NOW USE THEM
    XYZ.display();
    ABC.display();
    NNN.display();
    CCC.display();
    
    // USE gets AND sets TO MANAGE SCORES ...
    
    return 0;
}



My name is Mirmulnir Again, I am from the other Dragon  race, and I am FEMALE
My name is Mirmulnir, I am from the Dragon race, and I am MALE
My name is Lord Nord, I am from the NORD race, and I am FEMALE
My name is Poor Claude, I am from the NORD race, and I am MALE
Program ended with exit code: 0
All characters have abilities, but not all have Magicka.


So that means that the Character class should have the ability member, and all other classes should inherit it.

If some of the classes need Magicka, then create an abstract class called Magical which has the Magicka member. Then there could be 2 possibilities: 1. Magical is derived from Character, so classes that need magic can derive from Magical and still have all the properties of Character; 2. All classes that need magic can inherit from Character and Magical - but that is multiple inheritance and could cause other problems.

I am going to say this yet again: Write down in simple English which characters you are going have, and the things they can do, and how they interact. Only have 1 Player, 1 Enemy and 1 Weapon. Set up functions to implement how they interact. Keep it as simple as possible, get it working. Although againtry provided an excellent example of working code, showing race and gender, these things are surplus from the POV of starting with the most simple example. Consider leaving them out for now, but nothing stopping you adding that in later.

I agree with againtry you need to learn from a reputable source. Learn simple things first, then figure out how to combine them to do more complex things. You could be hampering your learning by taking on something like an RPG game, which sounds simple, but in reality it isn't, it becomes complex very quickly.

What I said before about how complex RPG games can be: Imagine you have only 2 players (on your side), and 2 Enemies against you, and your players have the same type of Weapon, and the enemies have the same method of attack. Already we have 8 interactions !! As soon as you increase the types of Weapons and types of Characters, this number of interactions grows quickly, never mind other complications such as magic.

One could get around this by only having 1 large Enemy, and lots of instances of a single type of friendly character (Bowmen say)which all have the same type of weapon (arrows). Introduce some randomness into the effectiveness of each shot, and see how long it takes for the enemy to die. That way, interactions are kept to a minimum, but it is still a little interesting, and reasonable first step in your gaming journey.
Just skimmed through the last few posts, apologies if I missed something important, but I wanted to say that these kinds of design issues have been thought about before. This is a part of designing your framework where your class hierarchy can really hamper your ability to produce good, extendable code.

Interesting blog series by Eric Lippert (who looks at things from a C# perspective, but these ideas can be applied to any language):
https://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/
https://ericlippert.com/2015/04/30/wizards-and-warriors-part-two/
https://ericlippert.com/2015/05/04/wizards-and-warriors-part-three/
https://ericlippert.com/2015/05/07/wizards-and-warriors-part-four/
https://ericlippert.com/2015/05/11/wizards-and-warriors-part-five/

Might also want to look into "entity component systems", there's lots of videos about the subject.
Last edited on
Thanks for the replies guys. So i'm looking at the site Jonnin suggested, and i'm going to go through it all and take notes. My ADHD is going to make it difficult but i'm going to do it. Any other website suggestions that teach good C++ form would be appreciated, preferably modern C++ (C++11-C++20).

I agree with againtry you need to learn from a reputable source. Learn simple things first, then figure out how to combine them to do more complex things.


Do you know of any articles or tutorials on a site that would teach this?

You could be hampering your learning by taking on something like an RPG game, which sounds simple, but in reality it isn't, it becomes complex very quickly.


I agree, I didnt want a fully working game, I was just using the character RPG Classes as an example since its easier for me to understand the hierarchy, but the implementation of it in actual code is where I get tangled up, so I need to just go back and learn more.

One could get around this by only having 1 large Enemy, and lots of instances of a single type of friendly character (Bowmen say)which all have the same type of weapon (arrows). Introduce some randomness into the effectiveness of each shot, and see how long it takes for the enemy to die. That way, interactions are kept to a minimum, but it is still a little interesting, and reasonable first step in your gaming journey.


Thats a good idea actually, maybe I could do it but i'm unsure, I think i should probably stick with going back and learning first. Creating one class isnt too hard, a class is a pretty simple concept, it's when I need to start inheriting and doing polymorphism is when it gets tricky.

and @Ganado i'll take a look at those articles, thanks!
dhayden wrote:
This is what 99% of getters and setters look like. yet they add no value over a public member, at the cost of obfuscation and reduced functionality. For example:
- you can't create a pointer or reference to the member, so you've actually reduced functionality.
- You can't do ++ or -- on the member
- You can't assign a value to it and use the result in an expression (like a=b=c)

I mean... yes, but that comes back to what I (and also TheIdeasMan) said about considering what functionality you want your class to supply to its clients, and designing that into the interface. If, having considered the functionality you want the class to offer, you decide need those things, then you design your interface to offer those things. And if you decide, in the context of the project you're working on, the most practical way to do that is simply to expose a public data member, then that's a reasonable option.

From my experience, though, there's genuine value in separating the interface from the implention. I've had times where I've needed to refactor code where the interface has simply exposed the implementation, and it's been vastly more work having to track down all the parts of the codebase that used that exposed implementation and rewrite those parts - than it would have been to just refactor the implementation knowing that the existing interface hides those changes. Putting some simple interface methods in place in the first place, is much less work than having to deal with the consequences of them being absent when it's time to refactor.

Obviously, if you're writing small, short-lived projects at home, this may not be a major issue for you (*). But when working on large codebases with a lifespan of years or even decades, particulary when writing core components used by multiple clients, it's an important consideration.

(That's the general *you*, not any specific poster here.)
Any other website suggestions that teach good C++ form would be appreciated, preferably modern C++ (C++11-C++20).

https://www.learncpp.com/
@OP
Do you know of any articles or tutorials on a site that would teach this?

These are a bit terse but they address inheritance comprehensively including the use of 'virtual' which will crop up very soon for you if not already:

https://docs.microsoft.com/en-us/cpp/cpp/single-inheritance?view=msvc-160

https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_71/rzarg/inher.htm#inher

There are plenty of other examples, some already mentioned.
Here's another one that advances forward to Factory Patterns which could be a longer term goal:
https://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
Awesome thanks! I'm currently reading through the LearnCPP.com site. I'll take a look at those as well.
Excellent. Another aspect to throw into the melting pot is UML and class diagrams that assist modelling and planning before writing code. Something to consider for the near future.
Good luck with it Ch1156
Topic archived. No new replies allowed.
Pages: 12