Function Users

Is there any way to, in a function, refer to the thing that called the function?
Such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <userrefer>

class Knickknak {
    public:
        std::string name;
        void thingy();
};

Knickknak::thingy() {
    Knickknak *i = Caller();
    std::cout << i.name << " is the Knickknack that called thingy.\n";
};

int main() {
    Knickknak theKnickknak;
    theKnicknak.name = "Fred"
    theKnickknak.thingy()
    return 0;
};


Which would display:
Fred is the Knickknak that called thingy.


Any way to do it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

class Knickknak {
    public:
        std::string name;
        void thingy();
};

Knickknak::thingy() {
    std::cout << name << " is the Knickknack that called thingy.\n";
};

int main() {
    Knickknak theKnickknak;
    theKnicknak.name = "Fred"
    theKnickknak.thingy()
    return 0;
};
Last edited on
Thanks! But...
What if a classA inherits from a classB (which contains thingy), and classA calls thingy?
The same thing :)
1
2
3
4
5
6
7
8
#incude "Human.h"

int main() {
    Human me(KrahkaMaster.hum);
    me.Say("OMG");
    me.Facepalm();
    return 0;
};
Look up the keyword this.
Would this.name (or this->name) return classA's name, or classB's?
It depends on the classes. If you're in a classA function, it will return classA's name. If you're in a classB function, it will return classB's name.

Although if you are inheriting, only the parent class should have a name. The derived class should not have a separate name. That way both classA and classB share the same name.
1
2
3
4
5
6
7
8
9
class B {
    public:
        std::string name;
};

class A : public B {
    public:
        std::int age;
}


1
2
3
4
5
6
7
8
A a;
B b;

a.name = "Acr"; //Class B has a name field, Class A inherits from B, so Class A also has a name field.
a.age = 12;

b.name = "Disch";
b.age = 1; // <---- Not possible! 

Last edited on
+1 @ Acr
Thanks guys!

But what if:
1
2
3
4
5
6
7
8
9
10
11
class B {
    public:
        std::string name;
        class* Caller(); // <---- Proper line?

};

class A : public B {
    public:
        std::int age;
};


1
2
3
4
5
6
7
A a;
B b;

class *ap = a.Caller()
class *bp = b.Caller()

std::cout << ap.name << '\n' << bp.name;




Topic archived. No new replies allowed.