Hello everyone.
I embarked on creating my first console application using classes.
I simplified my code but my problem boils down to creating multiple objects of a car class using input from the user using a variable. As soon as I create one object I can't seem to be able to access its members. In fact the code will not even compile. In contrast if I create an object by assigning specific identifier as in the second example everything works fine. Is there a way to access mpg member of a car object in the first example some other way?
class car{
public:
int mpg;
int max_speed;
};
example 1
int main(){
string i;
cin >> i;
car i;
i.mpg = 10;
Updated Question: is it possible to use a variable to create an object then?
I mean since I need to capture user input into a variable first and then use it to create the class object, I will always run into same issue. Any thoughts on that?
So what exactly happens if I do repeat declaration of a bmw car object. Do I have two instances of bmw? And if yes how would I differentiate between their members? Or is this also not allowed?
class car{
public:
std::string name;
int mpg;
int max_speed;
};
int main(){
int num;
std::string name;
car* ptr;
std::cout << "Number of cars: ";
std::cin >> num;
ptr = new car[num];
for (int i = 0; i < num; i++){
std::cout << "Enter name of car " << i + 1 << ": ";
std::cin >> name;
std::cout << std::endl;
ptr[i].name = name;
}
delete[] ptr;
return 0;
}
1. Provide a member variable which is the name of the object:
1 2 3 4 5 6 7
class car{
public:
std::string m_Make;
std::string m_Model;
int m_mpg;
int m_max_speed;
};
Although member variables should be private: You could use a struct (public by default), but make the object (or a collection of them )a private member of the another class.