Classes Lesson

Pages: 123
who is twicker?
The admin of this site.
like the one who wrote the tutorials and everything?
what does the constructor do for the class?
The constructor is usually created automatically by the compiler, but you can create your own, to initlialize the variables associated... soo... here goes my first attempt to help another with C++

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
class Dog(){

public:

	void bark();  //just a function...
	Dog(int );   //this is the constructor!

private:

	int barkDecibels;  // variable that tells you how annoying this dog is
};

Dog::Dog(int thisWillSetBarkDecibels)
{
	barkDecibels = thisWillSetBarkDecibels;  
       //you set this by calling in your main, or other function like:
       // dog chihuaha(5000);  // or
       //  dog Rottweiler(50);   // i hope you get the picture
}

void Dog::bark()
{
	loudnessOfBark = barkDecibels   // pretend this is a function that actually makes a dog bark
  	
}
Last edited on
It is a special function that is automatically called when you instantiate an object of a particular class. It basically sets the object up for use. A class may have many constructors (but only one destructor - that's another special function, that's automatically called when an object's life is finished). If you don't explicitly provide one, the compiler will provide you with a default constructor that does nothing (same goes for the destructor). 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
using namespace std;

class MyClass
{
public:

    int i;
    double d;
    string s;

    //default constructor, does nothing...
    //besides printing a message to prove
    //it was called :P
    MyClass()
    {
        cout << "Hi! I'm the default constructor!" << endl;
    }

    //another constructor...
    MyClass(int i_, double d_, string s_)
    {
        i=i_;
        d=d_;
        s=s_;

        cout << "Hi! I'm the other constructor!" << endl;
    }

    ~MyClass()
    {
        cout << "Yo! I'm the destructor!" << endl;
    }
};

int main()
{
    {
        //the default constructor is called
        MyClass my_object1;

        //the other constructor is called
        MyClass my_object2(1,0.5,"asdf");

        //both objects "die" now as they
        //go out of scope.
    }

    cout << "\nhit enter to quit";
    cin.get();
    return 0;
}

Last edited on
@SgtPooki: thanks :) but, are these parenthesis really supposed to be here? class Dog(){

@m4ster r0shi: thank a lot!! two questions: 1) Is it possible for both constructors to be called at the exact same time? 2) What is the point of making a deconstructor?
Is it possible for both constructors to be called at the exact same time?
No, but when a derive class (ie: voltron) inherits from a base class (ie: robot), the base class's (robot) default constructor get called first.

What is the point of making a deconstructor?
Usually use to free dynamically allocated memory.
@blackcoder41: Okay cool, but what do you mean by voltron and robot haha.
Wander wrote:
Is it possible for both constructors to be called at the exact same time?

No. Though there are cases (inheritance) where two (or more) constructors are called one just after the other. 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
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
#include <iostream>
using namespace std;

class Animal
{
public:

    Animal()
    {
        cout << "Animal constructor" << endl;
    }

    ~Animal()
    {
        cout << "Animal destructor" << endl;
    }
};

class Mammal: public Animal
{
public:

    Mammal()
    {
        cout << "Mammal constructor" << endl;
    }

    ~Mammal()
    {
        cout << "Mammal destructor" << endl;
    }
};

class Dog: public Mammal
{
public:

    Dog()
    {
        cout << "Dog constructor" << endl;
    }

    ~Dog()
    {
        cout << "Dog destructor" << endl;
    }
};

int main()
{
    {
        Dog rex;
    }

    cout << "\nhit enter to quit";
    cin.get();
    return 0;
}

Wander wrote:
What is the point of making a deconstructor?

A destructor usually takes care of the cleanup process at the end of the object's life, in most of the cases meaning deallocating memory that was dynamically allocated by the constructor or some other function of the class. 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;

class FooClass
{
public:

    FooClass()
    {
        cout << "FooClass constructor" << endl;
    }

    ~FooClass()
    {
        cout << "FooClass destructor" << endl;
    }
};

class BarClass
{
private:

    FooClass * foo_object;

public:

    BarClass()
    {
        cout << "BarClass constructor" << endl;

        //FooClass constructor is called here!
        foo_object=new FooClass();
    }

    ~BarClass()
    {
        cout << "BarClass destructor" << endl;

        //FooClass destructor is called here!
        delete foo_object;
    }
};

int main()
{
    {
        BarClass bar_object;
    }

    cout << "\nhit enter to quit";
    cin.get();
    return 0;
}

Try commenting out the delete statement and enjoy the memory leak you just created :P
Last edited on
@SgtPooki: thanks :) but, are these parenthesis really supposed to be here? class Dog(){


you're right! =x good catch haha =)
@blackcoder41: Okay cool, but what do you mean by voltron and robot haha
If you go deeper to classes, you'll learn about inheritance. Consider this
         ROBOT
    ______|___________
   |                  |
VOLTRON           MEGAMAN
                      |
                  ROCKMAN


Let's say someone invented a robot. Using that robot, you can create voltron and megaman by extending its capabilities. Just as you can create rockman base on megaman.

Sorry I'm lazy to write some example code now but m4ster r0shi gave you one any way..


+1 m4ster r0shi
Here is my code for my class. I'm getting some strange errors that I have no idea how to fix. I've tried to, but failed. haha.

MAIN:
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
#include <iostream> // I/O Streaming
#include <string>   // Strings, duh
#include <fstream>  // File Streaming
#include "StateCapital.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ios;
using std::ofstream;
using std::ifstream;

void ClearScreen() // Function used for clearing the screen
{
    cout << string( 100, '\n' );
}

int main()
{
    ifstream inFile; // Declare inFile
    ofstream outFile; // Declare outFile

    string troopList[29] = {"Spy", "Militia", "Swordsman", "Centurion", "Axe Thrower", "Bowman", "Longbowman", "Hussar", "Cavalry", "Paladin", "Battering Ram", "Ballista", "Catapult", "Goblin", "Prawn", "Orc", "Fire Beast", "Gorgon", "Lizard", "Witch", "Gargoyle", "Black Widow", "Vampire", "Butcher", "Demon", "Fallen", "Cyclops", "Troll", "Reaper"};

    StateCapital State_object;
}



CLASS:
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
#ifndef STATECAPITAL_H_INCLUDED
#define STATECAPITAL_H_INCLUDED

#include <iostream> // I/O Streaming

using namespace std;

class StateCapital {
    public:
    int spyAmount = 10000;
    int widowAmount = 30000000;
    int lizAmount = 25000000;
    int lbowAmount = 1000000;
    int reaperAmount = 10000;
    int ballAmount = 100000;
    int catAmount = 500000;

    StateCapital()
    {
        int spy_ = spyAmount;
        int widow_ = widowAmount;
        int liz_ = lizAmount;
        int lbow_ = lbowman;
        int reaper_ = reaperAmount;
        int ball_ = ballAmount;
        int cat_ = catAmount;
        cout << "constructor";
    }

    ~StateCapital()
    {
        cout<< "destuctor";
        delete State_object;
    }
};

#endif // STATECAPITAL_H_INCLUDED






|10|error: ISO C++ forbids initialization of member `spyAmount'|
|10|error: making `spyAmount' static|
|10|error: ISO C++ forbids in-class initialization of non-const static member `spyAmount'|
|11|error: ISO C++ forbids initialization of member `widowAmount'|
|11|error: making `widowAmount' static|
|11|error: ISO C++ forbids in-class initialization of non-const static member `widowAmount'|
|12|error: ISO C++ forbids initialization of member `lizAmount'|
|12|error: making `lizAmount' static|
|12|error: ISO C++ forbids in-class initialization of non-const static member `lizAmount'|
|13|error: ISO C++ forbids initialization of member `lbowAmount'|
|13|error: making `lbowAmount' static|
|13|error: ISO C++ forbids in-class initialization of non-const static member `lbowAmount'|
|14|error: ISO C++ forbids initialization of member `reaperAmount'|
|14|error: making `reaperAmount' static|
|14|error: ISO C++ forbids in-class initialization of non-const static member `reaperAmount'|
|15|error: ISO C++ forbids initialization of member `ballAmount'|
|15|error: making `ballAmount' static|
|15|error: ISO C++ forbids in-class initialization of non-const static member `ballAmount'|
|16|error: ISO C++ forbids initialization of member `catAmount'|
|16|error: making `catAmount' static|
|16|error: ISO C++ forbids in-class initialization of non-const static member `catAmount'|
||In constructor `StateCapital::StateCapital()':|
|23|error: `lbowman' was not declared in this scope|
|20|warning: unused variable 'spy_'|
|21|warning: unused variable 'widow_'|
|22|warning: unused variable 'liz_'|
|23|warning: unused variable 'lbow_'|
|23|warning: unused variable 'lbowman'|
|24|warning: unused variable 'reaper_'|
|25|warning: unused variable 'ball_'|
|26|warning: unused variable 'cat_'|
||In destructor `StateCapital::~StateCapital()':|
|33|error: `State_object' was not declared in this scope|
|33|warning: unused variable 'State_object'|
||In function `int main()':|
|24|warning: unused variable 'troopList'|
||=== Build finished: 23 errors, 10 warnings ===|

you're initializing your variables in your class. Do not do that.

Your class is only a blueprint, an idea..

It is just the bookshelf..

the data that is contained in it (the books that will fit), and in what manner they will fit, is your data.. which you will only know once you have the bookshelf...

1
2
3
4
5
6
7
8
9
  
public:
  int spyAmount;
    int widowAmount;
    int lizAmount;
    int lbowAmount;
    int reaperAmount;
    int ballAmount;
    int catAmount;


1
2
3
4
5
6
7
8
9
10
11
12
//remove all your constructor code.. or design the arguments to do the following
    StateCapital State_object;

//and because they are public, you do this
State_object.spyAmount =  10000;
State_object.widowAmount = 30000000;
State_object.lizAmount = 25000000;
State_object.lbowAmount = 1000000;
State_object.reaperAmount = 10000;
State_object.ballAmount = 100000;
State_object.catAmount = 500000;
What if I make them private? Then how would I change the value?

Also, can I change their value in the constructor?

EDIT: Am I suppose to put something about new in the constructor?
Last edited on
new allocates unused memory on your computer... don't worry about new yet...

you can change the value in the constructor as follows...

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
    StateCapital(int spy,  int widow, int liz)  
{
                                    //this is your constructor.. ~not default~ because you have defined
                                    // parameters  that need to be called to use this constructor
        spy_ = spy;
        widow_ = widow;
        liz_ = liz;
//etc.... 
    }


//then you can set them by 'initializing' the object with the above constructor.. as follows:

StateCapital this_is_a_state_capital(500/*value for spy*/, 100/*value for widow*/, 1 /*value for liz*/);

//or.. create a default constructor...

StateCapital()
{
//you already initialized all of these variables.. so now your computer knows what these are
// and you can define them
    spyAmount = 10000;  
    widowAmount = 30000000;
    lizAmount = 25000000;
    lbowAmount = 1000000;
    reaperAmount = 10000;
    ballAmount = 100000;
    catAmount = 500000;
}
THANKS so much!!! :D All of you guys! I don't think I have any more questions haha. If I do, I'll be sure to bug you guys. haha
Well, I officially suck at this hobby....

Anyways! I got farther with my class. I created a member function for it that get input from the user. Heres the code:

CLASS:
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#ifndef STATECAPITAL_H_INCLUDED
#define STATECAPITAL_H_INCLUDED

using namespace std;

class StateCapital {
    public:
    int spyAmount;
    int widowAmount;
    int lizAmount;
    int lbowAmount;
    int reaperAmount;
    int ballAmount;
    int catAmount;

    int getValues(int,int,int,int,int,int,int);

    StateCapital(int SC_spy, int SC_widow, int SC_liz, int SC_lbow, int SC_reaper, int SC_ball, int SC_cat)
    {
        StateCapital::getValues(spyAmount, widowAmount, lizAmount, lbowAmount, reaperAmount, ballAmount, catAmount);
        SC_spy = spyAmount;
        SC_widow = widowAmount;
        SC_liz = lizAmount;
        SC_lbow = lbowAmount;
        SC_reaper = reaperAmount;
        SC_ball = ballAmount;
        SC_cat = catAmount;
        cout << "constructor";
        cout << SC_spy;

    }

    ~StateCapital()
    {
        cout<< "destuctor";
       // delete State_object;
    }
};

int StateCapital::getValues(int spyAmount, int widowAmount, int lizAmount, int lbowAmount, int reaperAmount, int ballAmount, int catAmount)
{
    SC_troopInput:
    char yes_noOne;
    int input_choice;
    cout << "Choose a type of value to enter:" << endl << endl;
    cout << "1) SPY\n2) BLACK WIDOW\n3) LIZARD\n4) LONGBOWMAN\n5) REAPER\n6) BALLISTA\n7) CATAPULT\n";
    cin >> input_choice;

    switch (input_choice) {
        case 1: {
            cout << "How many spies are guarding a State Capital: ";
            cin >> spyAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }

        case 2: {
            cout << "How many black widows are guarding a State Capital: ";
            cin >> widowAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }

        case 3: {
            cout << "How many lizards are guarding a State Capital: ";
            cin >> lizAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }

        case 4: {
            cout << "How many longbowmen are guarding a State Capital: ";
            cin >> lbowAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }

        case 5: {
            cout << "How many reapers are guarding a State Capital: ";
            cin >> reaperAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }

        case 6: {
            cout << "How many ballistas are guarding a State Capital: ";
            cin >> ballAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }

        case 7: {
            cout << "How many catapults are guarding a State Capital: ";
            cin >> catAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }
    }

}

#endif // STATECAPITAL_H_INCLUDED 



MAIN:
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
#include <iostream> // I/O Streaming
#include <string>   // Strings, duh
#include <fstream>  // File Streaming
#include "StateCapital.h"

using namespace std;

void ClearScreen() // Function used for clearing the screen
{
    cout << string( 100, '\n' );
}

int main()
{
    int SC_spy;
    int SC_widow;
    int SC_liz;
    int SC_lbow;
    int SC_reaper;
    int SC_ball;
    int SC_cat;
    ifstream inFile; // Declare inFile
    ofstream outFile; // Declare outFile

    string troopList[29] = {"Spy", "Militia", "Swordsman", "Centurion", "Axe Thrower", "Bowman", "Longbowman", "Hussar", "Cavalry", "Paladin", "Battering Ram", "Ballista", "Catapult", "Goblin", "Prawn", "Orc", "Fire Beast", "Gorgon", "Lizard", "Witch", "Gargoyle", "Black Widow", "Vampire", "Butcher", "Demon", "Fallen", "Cyclops", "Troll", "Reaper"};

    StateCapital State_object(SC_spy, SC_widow, SC_liz, SC_lbow, SC_reaper, SC_ball, SC_cat);
}


PROBLEM:
Well, I tested it by just selecting the option to enter a value for the amount of spies:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int StateCapital::getValues(int spyAmount, int widowAmount, int lizAmount, int lbowAmount, int reaperAmount, int ballAmount, int catAmount)
{
    SC_troopInput:
    char yes_noOne;
    int input_choice;
    cout << "Choose a type of value to enter:" << endl << endl;
    cout << "1) SPY\n2) BLACK WIDOW\n3) LIZARD\n4) LONGBOWMAN\n5) REAPER\n6) BALLISTA\n7) CATAPULT\n";
    cin >> input_choice;

    switch (input_choice) {
        case 1: {
            cout << "How many spies are guarding a State Capital: ";
            cin >> spyAmount;
            cout << "Enter another troop number? y/n: ";
            cin >> yes_noOne;
            if (yes_noOne == 'y') {
                goto SC_troopInput;
            }
            else {
                break;
            }
        }


It all worked fine until I broke form the loop and it finished off the rest of the constructor. The value that it said I entered was some super high number in the 5 millions. The value I had entered was in the 30s. Haha. Sounds like a major problem to me. No idea what the problem is though.

BTW: If you're wondering what the heck these variable names are supposed to be, I'm basing this off of an online game I play on my Android phone. Haha!
the constructor is supposed to know what those variables are..

what is the point in passing the arguments if you are then going to call a function that gets what those arguments are supposed to be when the constructor is called?

And the Goto is honestly personal preference, if you can use it properly, I've heard pro's talk about it being ok.. very rarely.. but for your situation, it would be better to copy and paste your switch statement into another function called SC_troopInput(); and call that function instead of using goto.
I'm working on the constructor thing right now, but for the switch statement....

You want me to make two functions of the exact same thing and just alternate between the two instead of the goto? Also, what wrong with using goto?

, if you can use it properly,
suggests that I used in incorrectly. How am I supposed to use it?

Thanks
Pages: 123