PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, June 25, 2022

[FIXED] Why undeclared identifier error occurres while I'm using objet in class's function?

 June 25, 2022     c++, compiler-errors, oop     No comments   

Issue

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;

}

Solution

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.



Answered By - Anoop Rana
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing