Small help required :)

hello c++~ers,

I'm new with classes and functions. I am currently taking object oriented and I'd like to ask for some help :)

##################################################################################

#include <iostream>

using namespace std;

class print {

public:

int set_X();
int set_Y();
void print_something();

private:

int x;
int y;

};

int print::set_X(){

x=2;
return x;
};

int print::set_Y(){

y=2;
return y;
};

void print::print_something(){

cout << "Multiplying X and Y values gives you: "<< x*y << endl;

};

int main () {

print p;

p.print_something();


}

################################################################################

It returns a big number, so can you please clarify this for me?.

Thank you, in advanced :)
You didn't call set_X() or set_Y() so x and y are uninitialized and could be nothing or anything.
When you declared object of your class its members x and y were not initialized.

You could define your object as

print p = { 10, 20 };

if x and y were defined as public.

In your case before calling print_something you should set x and y with set_X and set_Y
Last edited on
your set_x and set_y functions seem a little confusing. The point is to set an x value and set a y value, why do they return and integer? i would go with something along the line of:
1
2
3
4
5
6
7
8
9
10
11
12
13
void set_x(int n)
{
x = n;
}

void set_y(int n)
{
y = n;
}

int get_x(){return x;}
int get_y(){return y;}
The number that you are seeing get printed out is just random garbage that happens to still be in the memory location where X is now staying. You should have a constructor that gets called to prevent this. It would also make for easier debugging.

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
class print {
public:
print() {
    this->x = 0;
    this->y = 0;
}

void set_x(int n) {
    this->x = n;
}

void set_y(int n) {
    this->y = n;
}
private:
int x;
int y;
};


int main() {
    print p();  //at this point, x and y both equal 0 because the constructor was called.

    p.set_x(5); //now, x = 5 and y = 0
    
}


Topic archived. No new replies allowed.