Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Classes-and-Objects-in-C

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including features such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It explains key principles like data encapsulation, the use of access specifiers, and provides code examples for better understanding. Additionally, it outlines different types of inheritance and polymorphism, emphasizing their importance in OOP.

Uploaded by

trytools5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Classes-and-Objects-in-C

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including features such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It explains key principles like data encapsulation, the use of access specifiers, and provides code examples for better understanding. Additionally, it outlines different types of inheritance and polymorphism, emphasizing their importance in OOP.

Uploaded by

trytools5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

@Naina

Unit 1: OOPs in CPP

1. OOP’s Features -Object, Classes,


2. Data Encapsulation & Abstraction, Delegation, Inheritance, Polymorphism,
Message Communication.
3. Class Specification, Defining Members,
4. Object, Access Specifier,
5. Constructors, types of Constructors, destructor,
6. Friend Class and Friend Function

1) Class:

 It is user defined datatype

 It is collection of data member and member function

 A class is a blueprint of object

 Class are created using “class” keyword

 When a class is declared no memory is allocated


@Naina

2) Object:

 An object is an instance of a class

 Object is a real world entity that can use for unique representation

 Object is a variable

 When object of a class is declared memory is allocated

 An Object is an instance of a class. It is a real-world entity with attributes


and behaviors, created based on a class.

Syntax: class_name object_name;


@Naina
@Naina

Program of class and object:


#include <iostream>
using namespace std;
// Define a class
class Car {
// Attributes (data members)
public:
string make;
string model;
int year;

// Methods (member functions)


public:
void startEngine() {
cout << "Engine started!" << endl;
}

void displayInfo() {
cout << "Make: " << make << ", Model: " << model << ", Year: " << year
<< endl;
}
};

int main() {
// Create an object of the Car class
Car myCar; // Object creation

// Assigning values to attributes of the object


myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2020;

// Calling methods of the object


myCar.startEngine();
myCar.displayInfo();

return 0;
}
@Naina

3) Encapsulation:

 Encapsulation is the concept of binding data (variables) and methods


(functions) that manipulate the data into a single unit called a class.

 It also restricts direct access to some of the object's components, making


them private and exposing only necessary methods to interact with the
object (via public methods).

 Real-Life Example:

Bank Account System: Balance should not be modified directly; it should


be accessed through deposit and withdraw functions.
@Naina

Example:
#include <iostream>
using namespace std;

class Student {
private:
string name; // Private data member

public:
void setName(string n) { // Setter function
name = n;
}

string getName() { // Getter function


return name;
}
};

int main() {
Student s;
s.setName("John Doe");
cout << "Student Name: " << s.getName() << endl;
return 0;
}
1. Header File Inclusion

#include <iostream>
using namespace std;
 #include <iostream>: This includes the input-output stream library, which
allows us to use cout (for output) and cin (for input).
 using namespace std;: This avoids writing std:: before cout and cin.

2. Class Definition

class Student {
private:
string name; // Private data member
 class Student: Defines a class named Student.
 private:: The name variable is declared private, meaning it cannot be
accessed directly outside the class.
@Naina

 Encapsulation: By keeping name private, we ensure that it can only be


accessed or modified through defined methods.

3. Public Methods (Getter & Setter)

public:
void setName(string n) { // Setter function
name = n;
}

string getName() { // Getter function


return name;
}
 public:: Marks the following methods as accessible from outside the class.
 void setName(string n): A setter function that assigns a value to the private
variable name.
 string getName(): A getter function that returns the value of name.
📌 Why Use Getter and Setter?
 They allow controlled access to private data, maintaining data security.
 Direct modification of name is prevented.

4. Main Function

int main() {
Student s; // Creating an object of class Student
 Student s;: An object s of class Student is created.
 Objects are instances of a class that store data and use methods.

s.setName("John Doe"); // Setting name using setter function


 Calls setName("John Doe") to assign "John Doe" to the name variable
indirectly.

cout << "Student Name: " << s.getName() << endl;


 Calls getName() to retrieve the stored name and print it using cout.

return 0;
}
 Returns 0, indicating successful execution.

5. Output
@Naina

Student Name: John Doe


 The program sets the name as "John Doe" and then prints it.

Key Takeaways
1. Encapsulation:
o Data (name) is hidden from direct access.
o Access is allowed only through setName() and getName().
2. Data Security:
o Prevents unauthorized modification of name.
3. Object-Oriented Programming (OOP) Principles:
o Uses class, objects, getter, and setter.

4) Abstraction:

 Data abstraction is one of the most essential and important features of


object-oriented programming in C++.

 Abstraction means displaying only essential information and ignoring the


details.

 Data abstraction refers to providing only essential information about the data
to the outside world, ignoring unnecessary details or implementation.

Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerator will increase the speed of the car or applying brakes will
@Naina

stop the car but he does not know how on pressing the accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.

 Abstraction is the concept of hiding unnecessary details and showing only


the essential features of an object.
 It helps in reducing complexity and improving code readability.
class Car {
public:
void startEngine() {
cout << "Starting the car engine..." << endl;
}
};

int main() {
Car myCar;
myCar.startEngine(); // User doesn't need to know how engine starts internally
return 0;
}
#include <iostream>
using namespace std;

class Calculator {
public:
int add(int a, int b) { // Public method (only essential details)
return a + b;
}
};

int main() {
Calculator calc;
cout << "Sum: " << calc.add(5, 3) << endl; // Output: Sum: 8
return 0;
}
Explanation:
 The user only interacts with the add() function.
 The internal working (how addition is performed) is hidden.
 This is abstraction, as it provides a simple interface to the user.
@Naina

5) Inheritance :

What is Inheritance?
 Inheritance is a feature of Object-Oriented Programming (OOP) that allows
one class to acquire properties and behaviors of another class.
 It helps in code reuse and reducing duplication.
Types of Inheritance in C++
1. Single Inheritance → One parent, one child. ✅ (Example above)
2. Multiple Inheritance → Child inherits from multiple parents.
3. Multilevel Inheritance → Grandchild inherits from child (which inherits
from parent).
4. Hierarchical Inheritance → Multiple child classes inherit from one parent.
5. Hybrid Inheritance → Combination of two or more types.
6. Subclass-derived class or superclass- base class

Real-Life Example of Inheritance

 A child inherits characteristics from their parents (like eye color, height).
 Similarly, in C++, a child class (derived class) inherits from a parent class (base class).

#include <iostream>
using namespace std;

// Base Class (Parent)


class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};

// Derived Class (Child)


class Dog : public Animal {
public:
void bark() {
cout << "The dog barks." << endl;
}
};
@Naina

int main() {
Dog d;
d.eat(); // Inherited function from Animal class
d.bark(); // Own function of Dog class
return 0;
}
Explanation
Animal is the Base Class (Parent)
 It has a function eat().
Dog is the Derived Class (Child)
 It inherits the eat() function from Animal.
 It has its own function bark().
Object d of Dog Class
 It can call both eat() (inherited) and bark() (own method).

Single Inheritance in C++:


When a class is derived from a single base class then the inheritance is called
single inheritance. For a better understanding, please have a look at the below
image.
@Naina

If we have a class A that is the Base class and another class B that is the
Derived class or child class and B is inheriting from A. Then such type of
inheritance is called Single Inheritance in C++. Suppose you have a class
Rectangle. From this class, we have written another class that is Cuboid as
shown in the below image.

 Hierarchical Inheritance in C++:


When more than one derived class is created from a single base class then it is
called Hierarchical inheritance.
@Naina

Now if you have a class A then from this class there is more than one class
inheriting from A i.e. B is inheriting, C is inheriting as well as a D is inheriting. So,
when more than one class is inheriting from a Single Base Class, then such a type
of inheritance is called Hierarchical Inheritance. Suppose we have a class called
Shape. We know that Rectangle, Triangle, Circle, and so on. All these are shapes.

 Multilevel Inheritance in C++:


When a derived class is created from another derived class, then that type of
inheritance is called multilevel inheritance. For a better understanding, please have
a look at the below image.

If there is a class A and from A, class B is inheriting and from B, class C is


inheriting, then such type of inheritance is called Multilevel Inheritance in C++.
Suppose we have a class called Point. We know the point is having some
coordinates i.e. x and y. And the radius of a point is zero.
@Naina

 Multiple Inheritance in C++:


When a derived class is created from more than one base class then such type of
inheritance is called multiple inheritances.

If there are classes A and B and from both of them class C is inheriting, then such
type of inheritance is called Multiple Inheritance in C++. There is a little different
compared to other inheritances. Multiple inheritance means our class can inherit
from more than one class in C++. So, it means for one class there can be more than
one base class. It is possible in C++ that a class can inherit from more than one
class.
@Naina

 Hybrid Inheritance in C++:

Hybrid Inheritance is the inheritance that is the combination of any single,


hierarchical, and multilevel inheritances

There are two subclasses i.e. B and C which are inheriting from class A. Then from
B and C there is one more class that is inheriting from B and C which is D.
Now this is a combination of hierarchical inheritance from the top and
multiple inheritances from the bottom. So, if you have this type of
inheritance then the features of base class A will be appearing in class D via
class B and class C.
@Naina

6) Polymorphism
 The word “polymorphism” means having many forms.
 In simple words, we can define polymorphism as the ability of a
message to be displayed in more than one form.
 A real-life example of polymorphism is a person who at the same time
can have different characteristics.
Ex:- A man at the same time is a father, a husband, and an employee. So the
same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of
Object-Oriented Programming.

Types of Polymorphism:

 Compile-time Polymorphism (also known as Static Polymorphism): This is


achieved through function overloading and operator overloading.

 Run-time Polymorphism (also known as Dynamic Polymorphism): This is


achieved through inheritance and virtual functions.
@Naina

Access specifier

In C++, access specifiers are used to control the visibility and accessibility of
members (variables and functions) of a class. The three main access specifiers in
C++ are:

1. Public:

 Members declared as public are accessible from anywhere, both inside and
outside the class.
 They can be accessed directly by creating an object of the class or through a
pointer/reference to the object.

class MyClass {
public:
int x;
void display() {
std::cout << "Value of x: " << x << std::endl;
}
};

int main() {
MyClass obj;
obj.x = 10; // Accessing public member
obj.display(); // Calling public method
}
2. Private:

 Members declared as private are accessible only within the class itself.
 They cannot be accessed directly outside the class, not even by derived
classes.
 This is used to encapsulate data and ensure that it is protected from
unauthorized access or modification.

class MyClass {
private:
int x; // Private variable
public:
void setX(int val) { x = val; } // Public method to set x
void display() {
@Naina

std::cout << "Value of x: " << x << std::endl;


}
};

int main() {
MyClass obj;
obj.setX(10); // Accessing private member through public method
obj.display();
// obj.x = 20; // Error: x is private and cannot be accessed directly
}
3. Protected:

 Members declared as protected are accessible within the class and its
derived classes.

 They are not accessible from outside the class unless through a member
function or friend class.

 This is useful when you want to allow derived classes to access base
class members, but still prevent direct access from outside the class.
class Base {
protected:
int x; // Protected member
public:
void setX(int val) { x = val; }
};
class Derived : public Base {
public:
void display() {
std::cout << "Value of x: " << x << std::endl; // Derived class can
access protected member
}
};
int main() {
Derived obj;
obj.setX(10);
obj.display();
// obj.x = 20; // Error: x is protected and cannot be accessed directly
outside of Derived
}
@Naina

Access Specifier Accessibility


Public Accessible from anywhere, inside or outside the class
Private Accessible only inside the class itself
Protected Accessible inside the class and its derived classes

These access specifiers help in controlling data encapsulation and information hiding, which are
fundamental principles in object-oriented programming.

You might also like