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

C++ Variable

C++ Variables: Named Storage Units In C++, variables serve as named boxes in memory that hold values during program execution. Each variable has three key aspects: 1. Data Type: Defines the kind of data a variable can store: numbers (integers, floating-point, etc.), characters, boolean values (true/false), or custom data structures (arrays, objects). Common data types: int : Whole numbers (e.g., -10, 0, 23) float : Decimal numbers (e.g., 3.14, -2.5) double : More precise decimal numbers char : Single characters (e.g., 'a', 'Z', '&') bool : True or false values 2. Name: A user-defined label for the variable, chosen according to naming conventions: Start with a letter or underscore. Contain letters, digits, and underscores. Case-sensitive (e.g.,  age  and  Age  are different). Not a reserved keyword (e.g.,  int ,  for ). Choose meaningful names that reflect the variable's purpose. 3. Value: The actual data stored in the variable, which must match its data...

C++ Data Types

C++ Data Types In C++, data types are crucial for defining the kind of information your variables can hold and the operations you can perform on them. They ensure memory allocation and prevent unexpected behavior. Here's a breakdown of the key data types: Fundamental Data Types: Integer:   int  - Used for whole numbers (negative, zero, or positive). Examples:  int age = 25; Floating-point:   float  and  double  - Represent decimal numbers.  float  offers less precision but faster processing, while  double  is more precise but slower. Examples:  float pi = 3.14159; double distance = 123.456789; Character:   char  - Stores single characters (letters, numbers, symbols). Examples:  char initial = 'A'; Boolean:   bool  - Represents true or false values. Examples:  bool isLoggedIn = true; Void:   void  - Indicates a lack of value. Primarily used...

C++ Functions

C++ Functions A function is a block of code that performs a specific task. Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem: a function to draw the circle a function to color the circle Dividing a complex problem into smaller chunks makes our program easy to understand and reusable. There are two types of function: Standard Library Functions:  Predefined in C++ User-defined Function:  Created by users In this tutorial, we will focus mostly on user-defined functions. C++ User-defined Function C++ allows the programmer to define their own function. A user-defined function groups code to perform a specific task and that group of code is given a name (identifier). When the function is invoked from any part of the program, it all executes the codes defined in the body of the function. C++ Function Declaration The syntax to declare a function is: returnType functionName (parameter1, parameter2,...) { // func...