Difference in functions when attached to an object

My question is why when I attach this function to an object, it produces a different result? If I attach div() to goose, it produces 4 as the value of alpha, but if it's not attached, it produces 3, why is this?
main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include "main.h"
using namespace std;

int main()
{
    Oreo fox;
    fox.div();
    fox.mod();
}

main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>
#include "main.h"
using namespace std;
Oreo goose;
int Oreo::div()
{
    alpha = 3;
    return 0;
}
int Oreo::mod()
{
    alpha = 4;
// The function in question.
    goose.div();
    cout << alpha;
    return 0;
}

main.h
1
2
3
4
5
6
7
8
9
10
11
#ifndef MAIN_H
#define MAIN_H

class Oreo
{
public:
    int alpha = 1;
    int div();
    int mod();
};
#endif // MAIN_H 

Non-static functions are always 'attached' to an object. They have to be.

1
2
3
4
5
6
7
8
9
10
// global goose.alpha == 1
int main()
{
    Oreo fox;  // fox.alpha == 1

    fox.div();   // fox.alpha == 3

    fox.mod();   // fox.alpha == 4
                 // but this also calls goose.div(), so goose.alpha == 3
}
1
2
3
4
5
6
7
8
int Oreo::mod()
{
    alpha = 4;
// The function in question.
    goose.div();
    cout << alpha;
    return 0;
}

1
2
3
4
5
6
7
int Oreo::mod()
{
    alpha = 4;
// The function in question.
    div();
    cout << alpha;
    return 0;

Why is it that the latter produces 3 instead of 4?
calling 'div' sets the alpha of its object to 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int Oreo::mod()  // assuming 'this' is 'fox'
{
    alpha = 4;  // fox.alpha = 4
// The function in question.
    goose.div();  // calls goose.div() .... goose.alpha = 3
    cout << alpha;  // print fox.alpha:  4
    return 0;
}


//...

int Oreo::mod()  // assuming 'this' is 'fox'
{
    alpha = 4;  // fox.alpha = 4
// The function in question.
    div();  // calls fox.div() .... fox.alpha = 3
    cout << alpha;  // print fox.alpha:  3
    return 0;


If you do not specify an object for the div call... the object used is this.
Last edited on
Because you call div() before you output alpha. div() changes the value of alpha to 3.
In main2.cpp, line 15 invokes div on a different object than that specified in your main function, so you don't see the results of that call.

http://ideone.com/f9Lz4v
Topic archived. No new replies allowed.