techmore.in

CPP Objects

In C++, objects are instances of classes, which are user-defined types. A class defines the properties (attributes) and behaviors (methods) that the object can have. When you create an object, you're essentially creating a specific instance of that class, with its own values for the properties and access to the behaviors.

Basic Structure of C++ Classes and Objects

Here’s a simple example:

cpp
#include using namespace std; // Define a class class Car { public: // Attributes (member variables) string brand; string model; int year; // Constructor Car(string b, string m, int y) { brand = b; model = m; year = y; } // Method (member function) void displayInfo() { cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl; } }; int main() { // Create objects of the Car class Car car1("Toyota", "Corolla", 2020); Car car2("Honda", "Civic", 2022); // Access object properties and methods car1.displayInfo(); car2.displayInfo(); return 0; }

Key Concepts

  1. Class: A blueprint for creating objects (instances).
  2. Object: An instance of a class.
  3. Constructor: A special method used to initialize objects.
  4. Methods: Functions defined inside a class that can operate on objects.