KEMBAR78
Oops Unit 3 | PDF | C++ | Object Oriented Programming
0% found this document useful (0 votes)
25 views16 pages

Oops Unit 3

Uploaded by

aviy82405
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)
25 views16 pages

Oops Unit 3

Uploaded by

aviy82405
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/ 16

Classes and Data Abstraction

Structure :
• A structure in C++ is a user-defined data type that groups related
variables of different data types together.
• It is used when multiple related variables need to be stored in a
single entity.

A structure is defined using the struct keyword.


Syntax:
struct StructureName {
dataType member1;
dataType member2;
// More members
};
Example:
#include <iostream>
#include <string>
using namespace std;

struct Person {
string name;
int age;
float height;
};

int main() {
Person p1; // Creating a structure variable

p1.name = "Xyz";
p1.age = 20;
p1.height = 5.6;

cout << "Name: " << p1.name << endl;


cout << "Age: " << p1.age << endl;
cout << "Height: " << p1.height << " feet" << endl;

return 0;
}

Structures within Structures (Nested Structures):


A structure can have another structure as a member.

#include <iostream>
using namespace std;

struct Address {
string city;
int pin;
};
struct Person {
string name;
Address addr;
};

int main() {
Person p1;
getline(cin,p1.name);
getline(cin,p1.addr.city);
cin>>p1.addr.pin;

cout << "Name: " << p1.name << ", City: " << p1.addr.city << ",
Pin: " << p1.addr.pin << endl;
return 0;
}
Typedef in Structure:
The typedef keyword is used to give a new name to a structure.(Not
required in C++).
typedef struct {
int rollNo;
char name[50];
} Student;

Student s = {225, "Abc"};


Array of Structures :
An array of structures is used to store multiple structure variables.
#include <iostream>
using namespace std;

struct Person {
string name;
int age;
};

int main() {
Person people[3]; // Array of 3 Person structures

// Input data
for (int i = 0; i < 3; i++) {
cout << "Enter name and age for person " << i + 1 << ": ";
cin >> people[i].name >> people[i].age;
}

// Display data
cout << "\nDetails of People:\n";
for (int i = 0; i < 3; i++) {
cout << "Name: " << people[i].name << ", Age: " <<
people[i].age << endl;
}

return 0;
}

Structure and Function :


Structures can be passed to functions by value or reference.

1. Pass by value
• In call by value, a copy of the structure is created inside the
function.
• Any changes made inside the function do not affect the original
structure.
#include <iostream>
using namespace std;

struct Person {
string name;
int age;
};

// Function to display Person details (Call by Value)


void display(Person p) { // Receives a copy of the structure
p.age += 5; // Changes will not affect the original structure
cout << "Inside Function (Modified Age): " << p.name << ", "
<< p.age << endl;
}

int main() {
Person p1 = {"Sunny", 25};

cout << "Before Function Call: " << p1.name << ", " << p1.age
<< endl;
display(p1); // Passing by value (Copy is created)
cout << "After Function Call: " << p1.name << ", " << p1.age
<< endl; // Original remains unchanged

return 0;
}
Pass by reference
• In call by reference, the function receives the actual structure,
not a copy.
• Any modification inside the function affects the original
structure.
#include <iostream>
using namespace std;

struct Person {
string name;
int age;
};

// Function to modify Person details (Call by Reference)


void modify(Person &p) { // Receives reference to the original
structure
p.age += 5; // This modifies the original structure
cout << "Inside Function (Modified Age): " << p.name << ", "
<< p.age << endl;
}

int main() {
Person p1 = {"Sunny", 30};

cout << "Before Function Call: " << p1.name << ", " << p1.age
<< endl;
modify(p1); // Passing by reference (No copy is created)
cout << "After Function Call: " << p1.name << ", " << p1.age
<< endl; // Original is changed

return 0;
}
Comparison: Pass by Value vs Pass by Reference:
Changes in
Method Memory Usage Original Performance
Structure?
Pass by High (Copies Slower for large
Value entire structure) No structures
Pass by Low (Only passes
Yes Faster
Reference address)
Class :
• A class is a blueprint for creating objects.
• It defines the attributes (data members) and behaviours (member
functions) that the objects of that class will have.

Object :
• An object is an instance of a class.
• A class is a blueprint, and an object is a real-world entity
created from that blueprint.
• Objects store data (in data members) and perform actions (using
member functions).

Example of a Class :
#include <iostream>
using namespace std;

class College { // Class definition


public:
string name; // College name
string location;
int establishedYear;

void displayInfo() { // Member function


cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;
}
};

int main() {
College myCollege; // myCollege is an Object of class College

// Assigning values
myCollege.name = "GEC Sheikhpura";
myCollege.location = "Sheikhpura";
myCollege.establishedYear = 2019;

// Calling member function


myCollege.displayInfo();

return 0;
}

Output :
College: GEC Sheikhpura
Location: Sheikhpura
Established: 2019
Key Features of Classes in C++
1. Data Members & Member Functions – Variables and functions that
operate on the data.
2. Constructors & Destructors – Special functions to initialize and
clean up objects.
3. Access Specifiers:
o public: Accessible from anywhere.
o private: Accessible only within the class.
o protected: Similar to private, but accessible in derived
classes.
4. Encapsulation – Data and functions are wrapped together.
5. Abstraction – Hiding the implementation details and only showing
the necessary functionality to the user.
6. Inheritance – A class can derive properties from another class.
7. Polymorphism – Allows methods to behave differently based on
object type.

Data Members (Class Variables)


• Data members are variables declared inside a class that store
information specific to an object.
• These variables help define the properties of an object.
class College {
public:
string name; // Data Member (Stores the name of the college)
string location; // Data Member (Stores the location)
int establishedYear;// Data Member (Stores the establishment year)
};

Member Functions (Class Methods)


• Member functions are functions declared inside a class that
define operations or actions related to the class.
• They manipulate and access the class’s data members.
class College { // Class definition
public:
string name; // data members
string location;
int establishedYear;

void displayInfo() { // Member function


cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;
}
};
Accessing Data Members & Member Functions
• Direct Access (Public Data Members)
o The dot (.) operator is used to access data members and
member functions.
• Private Data Members (Encapsulation)
o If data members are private, they cannot be accessed
directly.
o Instead, getter and setter functions are used.
o Object can access the public function, and the public
function can access the private data.

#include <iostream>
using namespace std;

class College {
public:
string name; // Public Data Member (Can be accessed directly)

private:
string location; // Private Data Member (Cannot be accessed directly)
int establishedYear; // Private Data Member (Cannot be accessed directly)

public:
// Setter Function (To set private data)
void setDetails(string loc, int year) {
location = loc;
establishedYear = year;
}

// Getter Function (To get private data)


void getDetails() {
cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;
}
};

int main() {
College myCollege;
// Directly Accessing Public Data Member
myCollege.name = "GEC Sheikhpura"; // ✅ Allowed (name is public)

// Attempt to Access Private Members Directly (❌ Error)


// myCollege.location = "Sheikhpura"; // ❌ Error: location is private
// myCollege.establishedYear = 2019; // ❌ Error: establishedYear is private

// Setting Private Data using Setter Function


myCollege.setDetails("Sheikhpura", 2019); // ✅ Allowed

// Getting and Displaying Data using Getter Function


myCollege.getDetails(); // ✅ Allowed

return 0;
}
Output :
College: GEC Sheikhpura
Location: Sheikhpura
Established: 2019

Types of Member Functions :


• Inside Class Definition
o The function is defined inside the class.
class College {
public:
void displayInfo() {
cout << "This is GEC Sheikhpura." << endl;
}
};
• Outside Class Definition
o The function is defined outside the class using the scope
resolution operator (::)
class College {
public:
void displayInfo(); // Function Declaration
};

// Function Definition Outside Class


void College::displayInfo() {
cout << "This is GEC Sheikhpura." << endl;
}

Accessor and Mutator Functions:


Accessor and Mutator functions are used to encapsulate class data by
controlling access to private member variables.

• Accessor Functions (Getters)


Accessor functions, also known as getters, are used to retrieve the
values of private or protected data members.
• Mutator Functions (Setters)
Mutator functions, also known as setters, are used to modify the values
of private or protected data members.

#include <iostream>
#include <string>
using namespace std;
class College {
private:
string name;
string location;
int establishedYear;
public:
// Accessor functions (getters)
string getName(){
return name;
}

string getLocation(){
return location;
}

int getEstablishedYear(){
return establishedYear;
}

// Mutator functions (setters)


void setName(string& newName) {
name = newName;
}

void setLocation(string& newLocation) {


location = newLocation;
}

void setEstablishedYear(int newYear) {


establishedYear = newYear;
}
};
int main() {
College college;

// Set values using mutator functions


college.setName("GEC Sheikhpura");
college.setLocation("Sheikhpura");
college.setEstablishedYear(2019);

// Access values using accessor functions


cout << "\nAccessing values using getters:" << endl;
cout << "Name: " << college.getName() << endl;
cout << "Location: " << college.getLocation() << endl;
cout << "Established Year: " << college.getEstablishedYear() << endl;

return 0;
}

Output :
Accessing values using getters:
Name: GEC Sheikhpura
Location: Sheikhpura
Established Year: 2019

Special Member Functions


• Constructor (Automatic Initialization)
o A constructor is a special member function of a class that
automatically gets called when an object is created. It is mainly
used to initialize data members of a class.
o ✔ Is automatically called when an object is created.
✔ Has the same name as the class.
✔ Does not have a return type (not even void).
✔ Can be overloaded (multiple constructors in a class).
✔ If no constructor is defined, C++ provides a default constructor
automatically.
Default constructor initializes:
✔ Primitive data types (int, float, etc.) → Garbage values (random
memory values).
✔ Non-primitive data types (like string) → Default values (empty string
for string).

#include <iostream>
using namespace std;

class College {
private:
string name; // Default: Empty String ""
string location; // Default: Empty String ""
int establishedYear; // Default: Garbage Value (Random Memory Value)

public:
void getDetails() {
cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;
}
};

int main() {
College myCollege; // Default Constructor (Implicit) Called

myCollege.getDetails(); // Uninitialized values will be printed

return 0;
}

Output :
College:
Location:
Established: 789456 <-- (Garbage Value)

o Explicitly define default constructor :

#include <iostream>
using namespace std;

class College {
private:
string name;
string location;
int establishedYear;

public:
// Default Constructor
College() {
name = "GEC Sheikhpura";
location = "Sheikhpura";
establishedYear = 2019;
cout << "Default Constructor Called!" << endl;
}
// Function to display details
void getDetails() {
cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;
}
};

int main() {
College myCollege; // Default Constructor Automatically Called
myCollege.getDetails(); // Display initialized values
return 0;
}

Output :
Default Constructor Called!
College: GEC Sheikhpura
Location: Sheikhpura
Established: 2019

o Parameterized Constructor
A parameterized constructor allows us to pass values during object
creation.
#include <iostream>
using namespace std;

class College {
private:
string name;
string location;
int establishedYear;

public:
// Parameterized Constructor
College(string n, string loc, int year) {
name = n;
location = loc;
establishedYear = year;
cout << "Parameterized Constructor Called!" << endl;
}

// Function to display details


void getDetails() {
cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;

}
};

int main() {
// Object creation with parameters (Constructor is
automatically called)
College myCollege("GEC Sheikhpura", "Sheikhpura", 2019);

myCollege.getDetails(); // Display details


return 0;
}

Output :
Parameterized Constructor Called!
College: GEC Sheikhpura
Location: Sheikhpura
Established: 2019

• Copy constructor
o A copy constructor in C++ is a special constructor that creates a
new object by copying an existing object.
o It is automatically invoked when:
▪ An object is initialized using another object →
College college2 = college1; // Copy constructor called
▪ An object is passed by value to a function.
void displayCollege(College c) {
// Copy constructor called (object passed by
value)
c.getDetails();
}
▪ An object is returned by value from a function.
College createCollege() {
College temp("GEC Sheikhpura", "Sheikhpura", 2019);
return temp; // Copy constructor called
}

Syntax:
ClassName(const ClassName &oldObject) {
// code to copy data from oldObject to the new object
}
▪ Takes a constant reference (const &) to prevent modification
of the original object.
▪ Copies values from oldObject to the new object.

Example:
#include <iostream>
using namespace std;

class College {
private:
string name;
string location;
int establishedYear;

public:
// Parameterized Constructor
College(string n, string loc, int year) {
name = n;
location = loc;
establishedYear = year;
cout << "Parameterized Constructor Called!" << endl;
}
// Copy Constructor
College(const College &c) {
name = c.name;
location = c.location;
establishedYear = c.establishedYear;
cout << "Copy Constructor Called!" << endl;
}

// Function to display details


void getDetails() {
cout << "College: " << name <<endl;
cout<< "Location: " << location <<endl;
cout<< "Established: " << establishedYear << endl;

}
};

int main() {
College college1("GEC Sheikhpura", "Sheikhpura", 2019);
College college2 = college1; // Copy Constructor is Called

cout << "\nDetails of College2 (Copied from College1):" << endl;


college2.getDetails(); // Display copied details

return 0;
}

Output :
Parameterized Constructor Called!
Copy Constructor Called!

Details of College2 (Copied from College1):


College: GEC Sheikhpura
Location: Sheikhpura
Established: 2019

• Shallow Copy vs. Deep Copy


By default, C++ performs a shallow copy, which means it only copies the
memory addresses, not actual data. This can be problematic when using
dynamic memory allocation (new).

Example of Shallow Copy (Problem with Dynamic Memory)


#include <iostream>
#include <cstring>
using namespace std;

class College {
public:
char* name;

// Parameterized Constructor
College(const char* n) {
name = new char[strlen(n) + 1]; // Allocate memory
strcpy(name, n);
}
// Default Copy Constructor (Shallow Copy)
College(const College &c) {
name = c.name; // Copies memory address (not the actual data)
}

void getDetails() {
cout << "College: " << name << endl;
}
};

int main() {
College college1("GEC Sheikhpura");
College college2 = college1;
// Shallow Copy (Both objects point to the same memory)

strcpy(college2.name, "Another College");


// Changes both college1 and college2!

college1.getDetails();
college2.getDetails();

return 0;
}

Output:
College: Another College
College: Another College

Solution: Deep Copy (Proper Copy Constructor)


A deep copy manually allocates new memory and copies data properly.
#include <iostream>
#include <cstring>
using namespace std;

class College {
public:
char* name;

// Parameterized Constructor
College(const char* n) {
name = new char[strlen(n) + 1]; // Allocate memory
strcpy(name, n);
}

// Deep Copy Constructor


College(const College &c) {
name = new char[strlen(c.name) + 1]; // Allocate new memory
strcpy(name, c.name); // Copy actual data
}

void getDetails() {
cout << "College: " << name << endl;
}
~College() { // Destructor to free memory
delete[] name;
}
};

int main() {
College college1("GEC Sheikhpura");
College college2 = college1; //Deep Copy (Creates a separate copy)

strcpy(college2.name, "Another College"); //Only modifies college2

college1.getDetails(); // Original remains unchanged


college2.getDetails(); // Modified copy

return 0;
}

Output :
College: GEC Sheikhpura
College: Another College

• Destructor:
A destructor is a special member function of a class that is automatically
called when an object of the class goes out of scope or is explicitly
deleted.
✔ Same name as the class but prefixed with a tilde (~).
✔ No return type (not even void).
✔ Takes no parameters (cannot be overloaded).
✔ Automatically called when the object is destroyed.
✔ Used for resource deallocation (memory cleanup, closing files, etc.).

#include <iostream>
using namespace std;

class College {
private:
string name;
string location;
int establishedYear;

public:
// Constructor
College(string n, string loc, int year) : name(n), location(loc),
establishedYear(year) {
cout << "College " << name << " created at " << location << "
in " << establishedYear << "." << endl;
}

// Destructor
~College() {
cout << "College object destroyed." << endl;
}

};
int main() {
// Creating an object
College c("GEC Sheikhpura", "Sheikhpura", 2019);

return 0; // Destructor is called automatically here


}

Output:
College GEC Sheikhpura created at Sheikhpura in 2019.
College object destroyed.

When is a Destructor Called?


1. When an automatic (local) object goes out of scope.
2. When delete is called for a dynamically allocated object.
3. When a program terminates (for global/static objects).
4. When exit() is called (for global/static objects).
5. When a container (e.g., vector) holding objects is destroyed.

You might also like