Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Classes/Objects

Class

A class in programming is a blueprint or template for creating objects. It defines the structure and behavior that objects of that class will have.

Create a Object

To create a object we use class keyword:

class ClassName {
    // Access Specifier
    // Data Members (Attributes)

public:
    // Member Functions (Methods)
    // Constructors
    // Destructors
    // Other member functions
};

Example:

#include <iostream>
#include <string>
using namespace std;

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
  myObj.myNum = 10;
  myObj.myString = "Hello world!";

  // Print values
  cout << myObj.myNum << "\n"; 
  cout << myObj.myString; 
  return 0;
}

Output:

10
Hello world!

Multiple Objects

You can create multiple objects of one class:

Example:

#include <iostream>
#include <string>
using namespace std;

class Car {
  public:
    string brand;
    string model;
    int year;
};

int main() {
  Car carObj1;
  carObj1.brand = "AUDI";
  carObj1.model = "Q5";
  carObj1.year = 1990;

  Car carObj2;
  carObj2.brand = "ford";
  carObj2.model = "Everest";
  carObj2.year = 1989;

  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}

Output:;

AUDI Q5 1990
ford Everest 1989

    Leave a Reply

    Your email address will not be published.

    Need Help?