-1

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;

}
EMVI
  • 53
  • 1
  • 4
  • In the context of `car::enterCar`, there is no `carObj1` ; there is only `this` (which is implicit). Remove all the `carObj1.` from that function. Related, find the very best book you can. Trust me; that's mandetory. – WhozCraig May 08 '22 at 05:26
  • https://www.learncpp.com/cpp-tutorial/syntax-and-semantic-errors/ This is highly recommended site for beginners – erzya May 08 '22 at 05:30
  • @WhozCraig When we can not use it in our function so why should we use class object at all? – EMVI May 08 '22 at 05:31

1 Answers1

1

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.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • what is ```this``` ? – EMVI May 08 '22 at 05:59
  • @EMVI `this` is a pointer. Refer to [this pointer](https://learn.microsoft.com/en-us/cpp/cpp/this-pointer?view=msvc-170) and [here](https://en.cppreference.com/w/cpp/language/this) for more details. It is also explained in any beginner level [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason May 08 '22 at 06:02