Reputation: 58341
I would like to create a simple Car
class that has a Car::get
method that I can use to access private properties of the car with a string such as:
// Create Car Intance
Car myCar;
cout << myCar.get("wheels");
My problem is that I don't know how to point the private property with a dynamic variable. Here is the class:
// Libraries & Config
#include <iostream>
using namespace std;
// Create Car Class
class Car {
private:
int wheels = 4;
int doors = 5;
public:
Car(); // constructor
~Car(); // deconstructor
int get(string what); //
};
// Constructor
Car::Car(){ cout << "Car constructed." << endl; }
// Deconstructor
Car::~Car(){ cout << "Car deconstructed." << endl; }
// Get Method
int Car::get(string what){
// === THE PROBLEM ===
// How do I access the `wheels` property of the car class with the what argument?
return this[what] // ??
}
// Create Car Instance
Car myCar;
cout << myCar.get("wheels");
Upvotes: 1
Views: 919
Reputation: 48645
You can do something like this using a std::map
:
#include <map>
#include <string>
#include <iostream>
using namespace std;
class Car {
private:
std::map<std::string, int> parts = {{"wheels", 4}, {"doors", 5}};
public:
Car();
~Car();
int get(std::string what);
};
// Constructor
Car::Car(){ std::cout << "Car constructed." << endl; }
// Deconstructor
Car::~Car(){ std::cout << "Car deconstructed." << endl; }
// Get Method
int Car::get(string what){
return parts[what];
}
int main()
{
// Create Car Intance
Car myCar;
cout << myCar.get("wheels") << '\n';
}
It is worth reading up on exactly how a std::map
works here: http://en.cppreference.com/w/cpp/container/map
Upvotes: 2
Reputation: 10733
class Car {
private:
int wheels = 4; <<< This would flag an error as you cannot provide
int doors = 5; <<< in class initialization for non-consts.
int Car::get (string what)
{
if( what == "wheels" ) //// check for case sensitivity...
return wheels;
else
return doors;
}
Upvotes: 1