Skip to main content

OOP with C++ : Classes & Objects

OOP with C++: Classes & Objects

In C++ Object-Oriented Programming (OOP), classes act as blueprints for creating objects, which are individual instances of those blueprints. This concept forms the foundation of OOP, allowing you to model real-world entities and their behaviors within your code.

Understanding Classes:

  • A class defines the structure of its objects, including:
    • Data members: Variables representing the object's state or attributes (e.g., a car's model, year, color).
    • Member functions: Methods representing the object's behavior or actions (e.g., a car's start, stop, accelerate).
  • You can declare and define classes using the class keyword followed by the class name.

Creating Objects:

  • An object is an instance of a class, holding its own copy of data members and having access to member functions.
  • You create objects using the class name followed by the object name and a semicolon (;).
  • Example: Car myCar; creates an object named myCar of type Car.

Accessing Members:

  • Use the dot (.) operator to access an object's data members and member functions:
    • myCar.model = "Honda Civic"; sets the model data member of myCar.
    • myCar.start(); calls the start() member function of myCar.

Key OOP Concepts:

  • Encapsulation: Bundling data and methods together within a class, promoting data protection and hiding implementation details.
  • Inheritance: Creating new classes (subclasses) based on existing ones (superclasses), inheriting properties and potentially adding new ones.
  • Polymorphism: Enabling objects of different classes to respond to the same message in different ways, achieving flexible behavior.
  • Abstraction: Focusing on essential details and hiding complexity, creating reusable and easy-to-understand components.

Benefits of OOP:

  • Modular and organized code: Easier to understand, maintain, and reuse.
  • Realistic modeling: Objects represent real-world entities more naturally.
  • Flexibility and extensibility: Inheritance and polymorphism allow adapting code to new needs.
  • Data security: Encapsulation protects data integrity.

In C++, Object-Oriented Programming (OOP) is facilitated through classes and objects. Let's discuss classes and objects in C++:

Classes:

A class is a blueprint for creating objects. It defines the properties (data members) and behaviors (member functions) that objects of that class will have. Here's the basic syntax for defining a class in C++:

class ClassName { private: // Private data members and member functions protected: // Protected data members and member functions public: // Public data members and member functions };

Let's create a simple class called Person:

#include <iostream> #include <string> class Person { private: std::string name; int age; public: // Constructor Person(std::string n, int a) : name(n), age(a) {} // Member function to set name void setName(std::string n) { name = n; } // Member function to set age void setAge(int a) { age = a; } // Member function to display information void displayInfo() { std::cout << "Name: " << name << ", Age: " << age << std::endl; } };

Objects:

An object is an instance of a class. It represents a real-world entity that has attributes (data members) and behaviors (member functions) defined by its class. You can create multiple objects of the same class, each with its own set of data.

To create an object of a class, you use the class name followed by the object name and optional initialization parameters (if a constructor is defined):

ClassName objectName(initialization_parameters);

Using the Person class:

int main() { // Create objects of the Person class Person person1("Alice", 25); Person person2("Bob", 30); // Accessing member functions of objects person1.displayInfo(); person2.displayInfo(); // Modifying data members using member functions person1.setName("Charlie"); person1.setAge(35); person1.displayInfo(); return 0; }

Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35

In this example, Person is a class with data members name and age, along with member functions to set and display information. Two objects of the Person class (person1 and person2) are created, and their information is displayed using the member function displayInfo(). Then, the name and age of person1 are modified using the member functions setName() and setAge(), and the updated information is displayed.

Comments

Popular posts from this blog

Installation Steps

Download the Installer: Visit the website of the application you want to install and locate the download link for the Windows version. Usually, this will be an executable file (.exe) or a compressed file (.zip) containing the installer. Run the Installer: Once the installer file is downloaded, locate it in your downloads folder or wherever you saved it. Double-click on the installer file to run it. If it's a compressed file, extract its contents first and then run the installer. User Account Control (UAC) Prompt: Windows might display a User Account Control prompt asking for permission to make changes to your device. Click "Yes" to proceed with the installation. Setup Wizard: Most installers launch a setup wizard that guides you through the installation process. Follow the on-screen instructions which may involve accepting the license agreement, choosing the installation directory, and selecting any additional options or components you want to install. Installation Pr...

Spawning Processes of Linux OS

In Linux, spawning a process refers to the act of creating a new program execution instance. This essentially means creating a new child process from an existing parent process. Spawning allows for multitasking and running multiple programs concurrently on your system. Here's a breakdown of the mechanics: The core concept: Parent process:  The existing process that initiates the spawning. Child process:  The newly created process that inherits resources like memory and open files from the parent, but has its own execution path. The tools for spawning: fork() system call:  Creates a copy of the parent process, forming the basis for the child process. exec() system call:  Replaces the current process image with a new program, essentially loading and executing the child program within the child process. The two-step approach: fork():  Creates a near-identical copy of the parent process, including memory and file descriptors. This essentially duplicates the parent p...

DYNAMIC OBJECTS: New and Delete operators

Dynamic Memory Allocation in C++ with OOP: new and delete Operators Understanding the Need for Dynamic Memory: In C++, static memory allocation (on the stack) is suitable for objects whose size is known at compile time and lifespan is limited to the function scope. For objects whose size or lifetime cannot be determined until runtime, dynamic memory allocation (on the heap) using  new  and  delete  operators is crucial. Dynamic memory enables flexible object creation and destruction, often employed in data structures, linked lists, trees, etc. The new Operator: Allocates memory for an object of a specific type on the heap. Returns a pointer to the newly allocated memory. Can be used to create single objects ( new ObjectType ) or arrays ( new ObjectType[size] ). Syntax: C++ pointer_variable = new ObjectType(arguments); // Single object pointer_variable = new ObjectType[size](arguments); // Array Use code  with caution. content...