KEMBAR78
C++ Notes For CS Engineers Module-3 | PDF | Constructor (Object Oriented Programming) | Programming
0% found this document useful (0 votes)
3 views18 pages

C++ Notes For CS Engineers Module-3

The document explains the concepts of classes and structures in C++, highlighting their differences, syntax, and usage. It covers built-in operations on classes, including constructors, destructors, and operator overloading, as well as the importance of access specifiers and member functions. Additionally, it discusses the significance of reference parameters, accessor and mutator functions, and the role of friend classes and functions in accessing private members.

Uploaded by

prahladkumar3489
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 views18 pages

C++ Notes For CS Engineers Module-3

The document explains the concepts of classes and structures in C++, highlighting their differences, syntax, and usage. It covers built-in operations on classes, including constructors, destructors, and operator overloading, as well as the importance of access specifiers and member functions. Additionally, it discusses the significance of reference parameters, accessor and mutator functions, and the role of friend classes and functions in accessing private members.

Uploaded by

prahladkumar3489
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/ 18

Module-3.

Classes and Data Abstraction

Structure
In C++, a structure (or struct) is a user-defined data type that groups together different
variables under a single name. It's similar to a class, but by default, members of a struct
are public, whereas in a class they are private.

Syntax of Structure
struct StructureName
{
dataType member1;
dataType member2;
// more members
};
Example: Define and Use a Structure
#include <iostream>
using namespace std;

// Define a structure
struct Person
{
string name;
int age;
float height;
};

int main() {
// Declare and initialize a structure variable
Person person1;
person1.name = "SK";
person1.age = 35;
person1.height = 5.5;

// Access structure members


cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Height: " << person1.height << " feet" << endl;

return 0;
}
1
Class
In C++, a class is a user-defined data type that allows you to group data (variables) and
functions together into a single unit called an object. Classes are a core concept in

Object-Oriented Programming (OOP).


Unlike struct, members of a class are private by default, which means they can't be
accessed directly from outside the class unless specified as public.

Syntax of a Class
class ClassName {
private:
// Private data members (default)

public:
// Public data members or functions
};

Example: Define and Use a Class in C++


#include <iostream>
using namespace std;

// Define a class
class Car {
private:
string brand;
int year;

public:
// Method to set car details
void setDetails(string b, int y) {
brand = b;
year = y;
}

// Method to display car details


void displayDetails() {
cout << "Brand: " << brand << endl;
cout << "Year: " << year << endl;
}
};
2
int main() {
Car car1;

// Set car details


car1.setDetails("Toyota", 2020);

// Display car details


car1.displayDetails();

return 0;
}

Built-in Operations on Classes


In C++, built-in operations on classes refer to the automatic or default behaviors the
compiler provides for class objects unless you explicitly override them. These operations
include:

1. Object Creation and Destruction


• Constructor: Automatically called when an object is created.
• Destructor: Automatically called when an object goes out of scope or is deleted.

class Demo
{
public:
Demo() { cout << "Constructor called\n"; }
~Demo() { cout << "Destructor called\n"; }
};

2. Copy Constructor
• Automatically creates a new object as a copy of an existing object.
Demo d1;
Demo d2 = d1; // Copy constructor

3. Assignment Operator (=)


• Allows one object to be assigned to another of the same class.
Demo d1, d2;
d2 = d1; // Assignment operator

3
4. Address-of Operator (&)
• Can be used to get the address of an object.
Demo d;
Demo* ptr = &d;

5. Member Access Operators


• Dot operator (.): Access members through an object.
• Arrow operator (->): Access members through a pointer.
d1.show(); // using .
ptr->show(); // using ->

6. Sizeof Operator
• Returns the size of an object in bytes.
cout << "Size: " << sizeof(Demo);

7. Type Casts (when applicable)


• Can be used with friend functions or overloading if you define custom casting.

Optional: You Can Overload Operators


You can define how operators like +, ==, <, etc., behave for your class:

CopyEdit
class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) {}
Point operator+(const Point& p) {
return Point(x + p.x, y + p.y);
}
};

Assignment Operator and Classes


In C++, the assignment operator (=) is used to copy the contents of one object to
another of the same class. By default, C++ provides a default assignment operator that
performs a shallow copy, meaning it copies values member-by-member.

Basic Example: Default Assignment Operator


#include <iostream>
using namespace std;
4
class Box {
public:
int length;
int width;

void setDimensions(int l, int w) {


length = l;
width = w;
}

void display() {
cout << "Length: " << length << ", Width: " << width << endl;
}
};

int main() {
Box box1, box2;
box1.setDimensions(10, 5);

// Use assignment operator


box2 = box1;

box2.display(); // Output: Length: 10, Width: 5

return 0;
}

In this case, the default assignment operator is used. It works well for simple classes.

When to Overload the Assignment Operator


You must define (overload) the assignment operator when your class:
• Uses dynamic memory allocation (e.g., new / delete)
• Needs a deep copy (not just copying pointers)
• Manages resources like file handles, sockets, etc.
Example: Overloading Assignment Operator for Deep Copy
#include <iostream>
#include <cstring>
using namespace std;

5
class MyString {
private:
char* str;

public:
MyString(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}

// Copy Constructor
MyString(const MyString& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}

// Assignment Operator
MyString& operator=(const MyString& other) {
if (this == &other) return *this; // self-assignment check

delete[] str; // free old memory

str = new char[strlen(other.str) + 1];


strcpy(str, other.str);
return *this;
}

void display() {
cout << str << endl;
}

~MyString() {
delete[] str;
}
};

int main() {
MyString s1("Hello");
MyString s2("World");

6
s2 = s1; // assignment operator (deep copy)

s1.display(); // Hello
s2.display(); // Hello

return 0;
}

Class Scope
In C++, class scope refers to the visibility and lifetime of identifiers (variables, functions,
etc.) declared inside a class. Understanding scope is crucial for organizing access to class
members and ensuring encapsulation.

Key Aspects of Class Scope


1. Member Variables and Functions
All variables and functions declared inside a class are in the scope of that class.
class MyClass
{
int x; // x is in MyClass scope
public:
void setX(int val) { x = val; } // setX has access to x
int getX() { return x; }
};

2. Access Specifiers and Scope


C++ uses access specifiers to control how class members are accessed from outside the
class:
Specifier Scope Access Description

private Only inside the class (default in classes) Used for internal implementation
details
public Accessible from outside the class Used to expose interfaces

protected Like private, but accessible in derived Used in inheritance


classes.

3. Name Resolution and Class Scope


Within the class, functions can access members without using an object or the this pointer
explicitly.
7
class Counter
{
int count;

public:
void setCount(int c)
{
count = c; // refers to this->count
}
};

4. Nested Scope
You can nest classes inside another class — this is called nested class scope.
class Outer
{
public:
class Inner {
public:
void show() { cout << "Inside Inner class\n"; }
};
};

5. Qualified Names
To define a member function outside the class, you qualify it using the class scope:
class Demo
{
public:
void sayHello();
};

// Definition outside the class


void Demo::sayHello() {
cout << "Hello\n";
}

Reference Parameters and Class Objects


In C++, reference parameters allow functions to modify the original arguments passed
to them, rather than working on a copy. When dealing with class objects, using reference
parameters can:
• Improve performance (avoiding copying large objects)

8
• Allow modification of the original object (if passed by non-const reference)
• Ensure read-only access without copying (if passed by const reference)

Syntax Overview
void functionName(ClassName& obj); // by reference (modifiable)
void functionName(const ClassName& obj); // by const reference (read-only)

Example: Reference Parameter with Class Object


#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box(int l) : length(l) {}

void setLength(int l) {
length = l;
}

int getLength() const {


return length;
}
};

// Function to modify Box (non-const reference)


void updateBox(Box& b) {
b.setLength(20); // modifies the original object
}

// Function to display Box (const reference)


void displayBox(const Box& b) {
cout << "Length: " << b.getLength() << endl;
}

int main() {
Box myBox(10);

9
displayBox(myBox); // Length: 10
updateBox(myBox); // modifies myBox
displayBox(myBox); // Length: 20

return 0;
}

Why Use Reference Parameters?


Type Copies Object? Modifiable? Common Use
ClassName obj Yes Yes Simple or small objects
ClassName& obj No Yes Need to modify original object
const ClassName& obj No No Pass large objects read-only

Good Practice
• Use const ClassName& for read-only access to avoid unnecessary copying.
• Use ClassName& when you need to change the object.

Member Functions
In C++, member functions are functions that are defined inside a class and operate on
the objects of that class. They have access to the class’s data members (both public and
private).

Types of Member Functions


Type Description
Inside the class Defined directly in the class body
Outside the class Declared in the class, defined outside using scope
resolution (::)
Const member function Promises not to modify the object
Static member function Shared among all objects, doesn't require an object
Inline member function Defined inside the class — automatically inline
Example with All Basic Member Function Types
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

10
public:
// Constructor
Rectangle(int l, int w) {
length = l;
width = w;
}

// Member function defined inside class (inline)


int area() {
return length * width;
}

// Member function declared inside, defined outside


int perimeter() const;

// Static member function


static void description() {
cout << "This is a Rectangle class.\n";
}
};

// Definition outside the class using scope resolution


int Rectangle::perimeter() const {
return 2 * (length + width);
}

int main() {
Rectangle r(10, 5);

cout << "Area: " << r.area() << endl; // Inline member function
cout << "Perimeter: " << r.perimeter() << endl; // Outside definition
Rectangle::description(); // Static member function

return 0;
}

Special Member Function Keywords


• const: Prevents modification of the object inside the function.
• static: Belongs to the class, not a specific object.

11
• inline: Suggested for small functions (automatic if defined inside the class).

Accessor and Mutator Functions


In C++, accessor and mutator functions are used to encapsulate class data and control
how it's accessed or modified. This is a key part of data hiding in object-oriented
programming.

Definitions
Term Purpose Common Prefix
Accessor (Getter) Access (read) private data get
Mutator (Setter) Modify (write) private data set

Example: Accessor & Mutator Functions


#include <iostream>
using namespace std;

class Student {
private:
string name;
int age;

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

void setAge(int a) {
if (a > 0)
age = a;
else
cout << "Invalid age!" << endl;
}

// Accessor (Getter) functions


string getName() const {
return name;
}

int getAge() const {


12
return age;
}
};

int main() {
Student s;

// Set data using mutators


s.setName("Alice");
s.setAge(20);

// Get data using accessors


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

return 0;
}

Why Use Accessors and Mutators?


• Enforce validation (e.g. age > 0)
• Maintain data integrity
• Control read/write access
• Decouple internal representation from interface

Constructors
In C++, a constructor is a special member function of a class that is automatically
called when an object is created. Its main purpose is to initialize objects.
Key Features of Constructors
• Has the same name as the class
• No return type (not even void)
• Can be overloaded (multiple constructors with different parameters)
• Can be default, parameterized, or copy constructors

Types of Constructors
Type Description
Default No parameters, initializes with fixed/default values
Parameterized Takes parameters to initialize object uniquely
Copy Initializes an object as a copy of another

13
Example: All Constructor Types
#include <iostream>
using namespace std;

class Person {
private:
string name;
int age;

public:
// Default constructor
Person() {
name = "Unknown";
age = 0;
}

// Parameterized constructor
Person(string n, int a) {
name = n;
age = a;
}

// Copy constructor
Person(const Person& other) {
name = other.name;
age = other.age;
}

void display() const {


cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
Person p1; // default constructor
Person p2("Alice", 25); // parameterized constructor
Person p3 = p2; // copy constructor

p1.display(); // Name: Unknown, Age: 0


p2.display(); // Name: Alice, Age: 25
14
p3.display(); // Name: Alice, Age: 25 (copied from p2)

return 0;
}

In C++, a destructor is a special member function that is automatically called when an


object goes out of scope or is explicitly deleted. The main purpose of a destructor is to
clean up resources that were acquired during the lifetime of the object, such as dynamic
memory, file handles, or network connections.

Key Features of Destructors


• Same name as the class, but with a tilde (~) prefix.
• No return type (not even void).
• Cannot be overloaded (you can only have one destructor per class).
• Called automatically when an object goes out of scope or is deleted.

Example: Destructor in Action


#include <iostream>
using namespace std;

class MyClass {
private:
int* data; // dynamically allocated memory

public:
// Constructor: dynamically allocate memory
MyClass(int value) {
data = new int(value);
cout << "Constructor: Memory allocated with value " << *data << endl;
}

// Destructor: clean up memory


~MyClass() {
delete data; // free dynamically allocated memory
cout << "Destructor: Memory freed" << endl;
}

void display() {
cout << "Data: " << *data << endl;
}
15
};

int main() {
MyClass obj1(10); // Constructor called (memory allocated)
obj1.display(); // Display the value

// Destructor will be automatically called when obj1 goes out of scope


return 0;
}

Friend Class and Friend Functions


As we know that a class cannot access the private members of other class. Similarly a class
that doesn’t inherit another class cannot access its protected members.

Friend Class:
A friend class is a class that can access the private and protected members of a class in
which it is declared as friend. This is needed when we want to allow a particular class to
access the private and protected members of a class.

Function Class Example


In this example we have two classes XYZ and ABC. The XYZ class has two private data
members ch and num, this class declares ABC as friend class. This means that ABC can
access the private members of XYZ, the same has been demonstrated in the example
where the function disp() of ABC class accesses the private members num and ch. In this
example we are passing object as an argument to the function.

#include <iostream>
using namespace std;
class XYZ {
private:
char ch='A';
int num = 11;
public:
/* This statement would make class ABC
* a friend class of XYZ, this means that
* ABC can access the private and protected
* members of XYZ class.
*/
friend class ABC;
};
16
class ABC {
public:
void disp(XYZ obj){
cout<<obj.ch<<endl;
cout<<obj.num<<endl;
}
};

int main()
{
ABC obj;
XYZ obj2;
obj.disp(obj2);
return 0;
}

Output:
A
11
Friend Function:
Similar to friend class, this function can access the private and protected members of
another class. A global function can also be declared as friend as shown in the example
below:
Friend Function Example
#include <iostream>
using namespace std;
class XYZ
{
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj)
{
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
17
int main()
{
XYZ obj;
disp(obj);
return 0;
}
Output:
100
Z

18

You might also like