Passing an object's' method into a method of another object?
Sep 27, 2020 at 1:51pm UTC
Hi,
I'm wondering if its possible to do something in C++ which I'll show with the example below:
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class student
{
public :
int getAge() const ;
double getHeight() const ;
string getName() const ;
};
int student::getAge() const
{
return 38;
}
double student::getHeight() const
{
return 5.6;
}
string student::getName() const
{
return "James" ;
}
class Data
{
public :
student getData(student object) const ;
};
student Data::getData(student object) const
{
return object;
}
int main()
{
student james;
Data school;
cout << school(james.getName());
cout << "\n" << school(james.getAge());
cout << "\n" << school(james.getHeight());
}
I know this wont compile, but is it possible to do something like this? The idea is say I wanted to create a data base of students. Each student object has certain data in it like in this case an age, name and height. Then in the Data class I want to have a method that would return (or use) whichever function called from the student class that was passed to it
Sep 27, 2020 at 2:20pm UTC
I'm not sure what you really want, but consider:
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
#include <iostream>
#include <string>
using namespace std;
class student
{
public :
student(int a, double h, string n) : age(a), height(h), name(n) {}
int getAge() const { return age; }
double getHeight() const { return height;}
string getName() const { return name; }
int age;
double height;
string name;
};
template <typename T>
class Data
{
public :
T getData() const { return object; }
Data(const T& t) : object(t) {}
T object;
};
int main()
{
student james {38, 5.6, "James" };
student mat {42, 6.1, "Mathew" };
Data<student> schoolj {james};
cout << "\n" << schoolj.getData().getName();
cout << "\n" << schoolj.getData().getAge();
cout << "\n" << schoolj.getData().getHeight();
Data<student> schoolm {mat};
cout << "\n" << schoolm.getData().getName();
cout << "\n" << schoolm.getData().getAge();
cout << "\n" << schoolm.getData().getHeight();
}
If you explained what you were really trying to achieve, rather than how to do something we don't know why - we probably will be able to provide better info.
Last edited on Sep 27, 2020 at 2:23pm UTC
Sep 27, 2020 at 2:21pm UTC
I would ditch the Data class and go with something like
vector<student> school;
Sep 27, 2020 at 4:46pm UTC
>
cout << school(james.getName());
¿what's that supposed to print?
¿what benefit does the `school' wrapper give you?
here's an example on how to pass a member function pointer
https://stackoverflow.com/a/37500299
Topic archived. No new replies allowed.