0% found this document useful (0 votes)
3 views

oop2.0

The document provides an overview of key concepts in Object-Oriented Programming (OOP), including definitions and examples of objects, classes, encapsulation, inheritance, polymorphism, and more. It covers various OOP principles such as abstraction, constructors, destructors, and exception handling, along with advanced topics like templates, dynamic binding, and file I/O. Each concept is illustrated with code snippets to demonstrate its application in C++.

Uploaded by

m.physicist321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

oop2.0

The document provides an overview of key concepts in Object-Oriented Programming (OOP), including definitions and examples of objects, classes, encapsulation, inheritance, polymorphism, and more. It covers various OOP principles such as abstraction, constructors, destructors, and exception handling, along with advanced topics like templates, dynamic binding, and file I/O. Each concept is illustrated with code snippets to demonstrate its application in C++.

Uploaded by

m.physicist321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Object in OOP
**Definition**: An object is an instance of a class that represents a real-world entity. It contains data (attributes)
and methods (functions) that define its behavior.

**Example**:
An object of a Car class could have attributes like color and a method like `drive()`.

```cpp
Car myCar;
myCar.color = "Red";
myCar.drive();

2. Class in OOP
Definition: A class is a blueprint or template for creating objects. It defines the
attributes (data members) and behaviors (methods) that the objects will have.
Example:
A Student class could define attributes like name and age and a method like display().
cppCopy code
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

3. Encapsulation
Definition: Encapsulation is the concept of bundling data (attributes) and methods
(functions) that operate on the data into a single unit (class). It also restricts direct
access to some of the object's components.
Example:
Using private members and public methods in a BankAccount class ensures controlled
access.
cppCopy code
class BankAccount {
private:
int balance;
public:
void deposit(int amount) { balance += amount; }
};

4. Inheritance
Definition: Inheritance allows a class (child) to inherit attributes and methods from
another class (parent). It promotes code reuse and represents an "is-a" relationship.
Example:
A Dog class inherits common features from an Animal class.
cppCopy code
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};

class Dog : public Animal {


public:
void bark() { cout << "Barking..." << endl; }
};

5. Polymorphism
Definition: Polymorphism allows objects of different classes to be treated as objects of
a common base class. It enables methods to behave differently based on the object that
invokes them.
Example:
A Dog and a Cat class can override the sound() method from a base Animal class.
cppCopy code
class Animal {
public:
virtual void sound() { cout << "Animal sound" << endl; }
};

class Dog : public Animal {


public:
void sound() override { cout << "Bark" << endl; }
};

6. Abstraction
Definition: Abstraction hides unnecessary details and shows only essential features. It
simplifies complex systems by modeling classes appropriate to the problem.
Example:
A Calculator class exposes only the add() method without revealing how addition is
performed.
cppCopy code
class Calculator {
public:
int add(int a, int b) { return a + b; }
};

7. Constructor
Definition: A constructor is a special method that is automatically called when an object
is created. It is used to initialize the object's data members.
Example:
A Car class initializes its brand attribute when an object is created.
cppCopy code
class Car {
public:
string brand;
Car(string b) { brand = b; }
};

8. Destructor
Definition: A destructor is a special method that is automatically called when an object
is destroyed. It is used to release resources.
Example:
A Student class destructor displays a message when an object is destroyed.
cppCopy code
class Student {
public:
~Student() { cout << "Object destroyed" << endl; }
};

9. Friend Function
Definition: A friend function is a function that is not a member of a class but can access
its private and protected members.
Example:
A friend function printLength() accesses the private member length of a Box class.
cppCopy code
class Box {
private:
int length;
public:
friend void printLength(Box b);
};

10. Function Overloading


Definition: Function overloading allows multiple functions with the same name but
different parameters.
Example:
The print() function is overloaded to handle different data types.
cppCopy code
void print(int i) { cout << "Integer: " << i << endl; }
void print(double d) { cout << "Double: " << d << endl; }

11. Operator Overloading


Definition: Operator overloading allows defining custom behavior for operators like +, -,
*, etc., for user-defined types.
Example:
A Complex class overloads the + operator to add two complex numbers.
cppCopy code
class Complex {
public:
int real, imag;
Complex operator + (Complex const &obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
};

12. Exception Handling


Definition: Exception handling allows dealing with runtime errors using try, catch, and
throw blocks.
Example:
A division operation throws an exception when dividing by zero.
cppCopy code
try {
if (b == 0) throw "Division by zero!";
cout << a / b << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}

13. Templates
Definition: Templates allow writing generic functions and classes that can work with
any data type.
Example:
A generic add() function can work with integers, floats, or other data types.
cppCopy code
template <typename T>
T add(T a, T b) { return a + b; }

14. Dynamic Binding


Definition: Dynamic binding (or late binding) allows the method to be called to be
determined at runtime, based on the object type.
Example:
A base class pointer calls the overridden method of the derived class.
cppCopy code
class Animal {
public:
virtual void sound() { cout << "Animal sound" << endl; }
};

class Dog : public Animal {


public:
void sound() override { cout << "Bark" << endl; }
};

15. Abstract Class


Definition: An abstract class is a class that cannot be instantiated and contains at least
one pure virtual function.
Example:
A Shape class defines a pure virtual function draw() that derived classes must
implement.
cppCopy code
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

16. Static Members


Definition: Static members are shared among all objects of a class. They belong to the
class itself, not to any specific object.
Example:
A Counter class uses a static data member count to keep track of the number of objects
created.
cppCopy code
class Counter {
public:
static int count;
Counter() { count++; }
};
int Counter::count = 0;

17. Association
Definition: Association is a relationship between two classes where one class uses or
interacts with another class.
Example:
A Driver class interacts with a Car class.
cppCopy code
class Driver {
public:
void drive(Car car) { cout << "Driving " << car.model << endl; }
};

18. Aggregation
Definition: Aggregation is a "has-a" relationship where one class contains objects of
another class, but the contained objects can exist independently.
Example:
A University class contains Department objects that can exist independently.
cppCopy code
class Department {
public:
string name;
};

class University {
public:
vector<Department> departments;
};

19. Composition
Definition: Composition is a strong "has-a" relationship where the contained objects
cannot exist independently of the container.
Example:
A Car class contains an Engine object that cannot exist without the Car.
cppCopy code
class Engine {
public:
string type;
};

class Car {
public:
Engine engine; // Engine cannot exist without Car
};

20. Pointers to Objects


Definition: A pointer to an object stores the memory address of an object, allowing
indirect access to its members.
Example:
A pointer to a Car object calls its drive() method.
cppCopy code
Car myCar;
Car* ptr = &myCar;
ptr->drive();

21. Dynamic Memory Allocation


Definition: Dynamic memory allocation allows allocating memory for objects at runtime
using new and releasing it using delete.
Example:
An integer is allocated dynamically and then deleted.
cppCopy code
int* ptr = new int;
*ptr = 10;
delete ptr;

22. Copy Constructor


Definition: A copy constructor is used to create a new object as a copy of an existing
object.
Example:
A Student class defines a copy constructor to copy data from another object.
cppCopy code
class Student {
public:
Student(const Student &obj) { name = obj.name; }
};

23. Virtual Destructor


Definition: A virtual destructor ensures that the destructor of the derived class is called
when deleting an object through
Example**:
A base class defines a virtual destructor to properly release resources of the derived class.

```cpp
class Base {
public:
virtual ~Base() { cout << "Base destructor" << endl; }
};

24. Streams in C++


Definition: Streams are used for input/output operations in C++. Examples include cin,
cout, and file streams.
Example:
A program reads a value using cin and writes it using cout.
cppCopy code
int x;
cout << "Enter a number: ";
cin >> x;
cout << "You entered: " << x << endl;

25. Default Values for Functions


Definition: Default values for functions allow you to assign a value to a function's
parameter in advance. If no argument is provided for that parameter, the default value is
used.
Example:
A function printMessage() with a default value for the message parameter:
cppCopy code
void printMessage(string message = "Hello, World!") {
cout << message << endl;
}

26. Inline Functions


Definition: An inline function is a function where the function body is expanded in place
at the point where it is called, reducing the overhead of function calls.
Example:
An inline function to calculate the square of a number:
cppCopy code
inline int square(int x) { return x * x; }

27. Open Parameter List


Definition: An open parameter list allows a function to accept a variable number of
arguments, making it flexible for handling diverse inputs.
Example:
A function sum() using std::initializer_list to accept multiple arguments:
cppCopy code
int sum(initializer_list<int> numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}

28. References in C++


Definition: A reference is an alias for an existing variable. It allows you to access and
modify the original variable directly without creating a copy.
Example:
A reference ref pointing to variable a:
cppCopy code
int a = 10;
int &ref = a;
ref = 20; // Modifies a

29. Friend Classes


Definition: A friend class is a class that can access the private and protected members
of another class. It is declared using the friend keyword.
Example:
A FriendClass accessing private data of a Box class:
cppCopy code
class Box {
private:
int length;
friend class FriendClass;
};

30. Static Class Members


Definition: Static members in a class are shared among all objects of the class. They
belong to the class itself, not to any specific object.
Example:
A Counter class uses a static member count to track object creation:
cppCopy code
class Counter {
public:
static int count;
Counter() { count++; }
};

int Counter::count = 0;

31. Generalization and Specialization


Definition:
 Generalization: Combining common features of multiple classes into a single parent class.
 Specialization: Adding unique features to a derived class to make it more specific.
Example:
A Vehicle class generalized from Car and Bike, while Car specializes further with unique
features:
cppCopy code
class Vehicle {
public:
void start() { cout << "Vehicle started" << endl; }
};
class Car : public Vehicle {
public:
void drive() { cout << "Car is driving" << endl; }
};

32. Construction and Destruction in Inheritance


Definition: When a derived class object is created, the base class constructor is called
first, followed by the derived class constructor. During destruction, the derived class
destructor is called first, followed by the base class destructor.
Example:
A Derived object outputs the construction and destruction order:
cppCopy code
class Base {
public:
Base() { cout << "Base constructor" << endl; }
~Base() { cout << "Base destructor" << endl; }
};

class Derived : public Base {


public:
Derived() { cout << "Derived constructor" << endl; }
~Derived() { cout << "Derived destructor" << endl; }
};

33. Pointing Down the Hierarchy


Definition: Pointing down the hierarchy refers to using a base class pointer or
reference to point to objects of derived classes, enabling polymorphism.
Example:
A base class pointer points to a derived class object and calls its overridden methods:
cppCopy code
class Animal {
public:
virtual void display() { cout << "Animal class" << endl; }
};

class Dog : public Animal {


public:
void display() override { cout << "Dog class" << endl; }
};

34. Virtual and Pure Virtual Methods


Definition:
 Virtual Method: A method in the base class that can be overridden in derived classes.
 Pure Virtual Method: A method with no implementation in the base class, making the class
abstract.
Example:
A Shape class with a pure virtual method draw() and a Circle class implementing it:
cppCopy code
class Shape {
public:
virtual void draw() = 0; // Pure virtual method
};

35. File Input/Output Using Streams


Definition: File I/O allows reading from and writing to files using ifstream (input file
stream) and ofstream (output file stream).
Example:
Writing to and reading from a file:
cppCopy code
ofstream outFile("example.txt");
outFile << "Hello, File!" << endl;
outFile.close();

ifstream inFile("example.txt");

You might also like