C++ Objects

We have talked about Classes In the previous Tutorial.

An object is an instance of a class.

No memory is allocated when a class is specified, but it is allocated when it is instantiated (i.e., when an object is formed).

Code:



  #include "iostream"
  #include "string"
  using namespace std;

  class Car {
    public:

    string brand;
    string model;
    int year;
  };


  int main() {
    // Create an object of class "Car"
    Car myObj;

    // Access attributes and set values
    myObj.year = 2021;
    myObj.brand = "General Motors";
    myObj.model = "Cadillac";

    cout << myObj.year << "\n";
    cout << myObj.brand << "\n";
    cout << myObj.model;
  return 0;

            }
          

Output:


2021
General Motors
Cadillac

Type the class name, followed by the object name, to create an object of Car.

Use the dot syntax (.) on the object to access year, brand, and Model, which are class attributes.






© Copyright 2022 Advanced PLC. All rights reserved.