I've been self teaching CPP OOP and this error occurred: Error C2065 'carObj1': undeclared identifier
And since I'm self teaching I tried to search on Internet but nothing found! Can anyone help me with this?
#include <iostream>
#include <string>
using namespace std;
class car {
public:
string brand;
string model;
int year;
void enterCar() {
cout << "\nYour car is:" << carObj1.brand << " MODEL:" << carObj1.model << " BUILT-IN:" << carObj1.year;
}
};
int main()
{
car carObj1;
cout << "Enter your car's brand name:\n";
cin >> carObj1.brand;
cout << "Enter your car's Model:\n";
cin >> carObj1.model;
cout << "Enter your car's Built-in year:\n";
cin >> carObj1.year;
carObj1.enterCar();
return 0;
}
CodePudding user response:
The problem is that you're trying to access the fields brand
, model
and year
on an object named carObj1
which isn't there in the context of the member function car::enterObj
.
To solve this you can either remove the name carObj1
so that the implicit this
pointer can be used or you can explicitly use the this
pointer as shown below:
void enterCar() {
//-------------------------------------------vvvvv-------------->equivalent to writing `this->brand`
std::cout << "\nYour car is:" << brand <<std::endl;
//-----------------------------------vvvvvv------------------->explicitly use this pointer
std::cout<< " MODEL:" << this->model << std::endl;
std::cout<<" BUILT-IN:" << this->year;
}
Also i would recommend learning C using a good C book.