0% found this document useful (0 votes)
10 views32 pages

C++ Syllabus

The document outlines the curriculum for the B.Tech (CSE (DS)) Programming with C++ course at Aditya University for 2024, detailing course outcomes, practice modules, and key concepts. It covers fundamental C++ topics including recursion, classes, inheritance, and advanced concepts like templates and exception handling. The course aims to equip students with practical programming skills and a deep understanding of C++ programming principles.

Uploaded by

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

C++ Syllabus

The document outlines the curriculum for the B.Tech (CSE (DS)) Programming with C++ course at Aditya University for 2024, detailing course outcomes, practice modules, and key concepts. It covers fundamental C++ topics including recursion, classes, inheritance, and advanced concepts like templates and exception handling. The course aims to equip students with practical programming skills and a deep understanding of C++ programming principles.

Uploaded by

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

Aditya University

B.Tech (CSE (DS)) Curriculum – 2024


Course Title: Programming with C++
Course Code: 241A1033
Level: IC
L-T-P: 0-0-2
Credits (C): 2
CIE: 50
SEE: 50
Total Marks: 100
Pre-requisite: None

Course Outcomes (COs):


At the end of the course, the student will be able to:
 CO1: Apply C++ programming concepts like recursion, functions, and scope
resolution in problem-solving.
 CO2: Design programs using classes, encapsulation, access specifiers, constructors,
destructors, and operator overloading.
 CO3: Analyse forms of inheritance and polymorphism to build flexible and reusable
code components.
 CO4: Utilize C++ features like templates, exception handling, and STL containers to
create generic, robust, and high-performance applications.
 CO5: Develop a deep understanding of memory management, pointers, and virtual
base classes to solve problems involving complex inheritance and runtime behaviours
in C++.
CO-PO Mapping:
CO / PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11
CO1 3 2 2 1 1 1 1
CO2 3 3 2 1 2 1 1
CO3 3 2 3 2 1 1
CO4 3 3 2 2 3 1 1
CO5 3 3 3 2 3 1

CO-PSO Mapping:
CO / PSO PSO1 PSO2
CO1 2
CO2 2
CO3 2
CO4 2
CO5 2

Practice Modules:
1. Fundamental Concepts of C++
 Recursion: Write a program to find the factorial of a number using recursion.
 Call by Value and Call by Reference: Develop a C++ program to demonstrate both.
2. Scope Resolution and Namespaces
 Use global vs local variables, scope resolution operator, custom namespaces.
 Program to demonstrate scope resolution and use of namespaces.
3. Inline Functions
 Definition, syntax, benefits, when not to use.
 Create a program illustrating inline functions.
4. Classes, Objects, and Encapsulation
 Model a Bank Account with data members and functions (deposit, withdraw, display).
 Access Specifiers: Public vs Private – create a sample program.
 this Pointer: Use to resolve naming conflicts.
5. Function Overloading
 Define multiple functions with same name but different parameters.
 Use of default arguments.
 Friend Function to access private data.
6. Constructors and Destructors
 Create a class demonstrating default constructor and destructor.
 Constructor overloading and copy constructor with examples.
7. Operator Overloading
 Unary and binary operator overloading using member functions and friend functions.
8. Inheritance Types
 Single, multiple, multilevel, hierarchical, hybrid inheritance – one program each.
9. Constructor & Destructor Execution Order
 Demonstrate chaining of constructors and destructors in inheritance.
10. Pointers and Virtual Base Class
 Pointers to objects and accessing members.
 Resolve diamond problem using virtual base class.
11. Virtual Functions & Runtime Polymorphism
 Demonstrate function overriding and dynamic dispatch with base class pointers.
12. Templates
 Function templates and class templates – create programs for both.
13. Exception Handling
 Try, catch, throw mechanisms.
 Multiple catch blocks to handle different exceptions.
14. STL Containers
 List and Vector: insertion, deletion, traversal.
 Deque: implement and demonstrate basic operations.
 Map: perform insertion, deletion, access, and searching.

Additional Practice Exercises:


1. Flight Booking System – Create a complete C++ program.
2. Qt Application: Slider & Spin Box Sync – UI-based application.
3. Qt Application: Text Pad – A simple text editor.
4. Guessing Game with Asterisks
o Word guessing with maximum 3 wrong attempts.
o Sample output should demonstrate character replacement after each guess.
Introduction to C++: Key Concepts Outline
I. Getting Started with C++
A. What is C++?
1. A general-purpose, high-performance, object-oriented programming language.
2. Developed by Bjarne Stroustrup, an extension of the C language.
B. Why Learn C++?
1. Performance-critical applications (game engines, operating systems, embedded systems).
2. System programming.
3. Large-scale software development.
4. Understanding lower-level programming concepts.
C. Setting up your Development Environment
1. Compiler (GCC/G++, Clang, MSVC).
2. Integrated Development Environment (IDE) (Code::Blocks, VS Code, Visual Studio,
Eclipse CDT).
D. Basic Program Structure
1. #include <iostream>: Preprocessor directive for input/output.
2. int main(): The entry point of every C++ program.
3. std::cout << "Hello, World!";: Output to console.
4. return 0;: Indicates successful program execution.
5. Comments: Single-line (//) and multi-line (/* ... */).

II. Fundamentals of C++


A. Variables and Data Types
1. Primitive Data Types:
a. int: Integers.
b. float, double: Floating-point numbers.
c. char: Single characters.
d. bool: Boolean values (true/false).
e. void: Absence of type.
2. Type Qualifiers (const, volatile).
3. Variable Declaration and Initialization.
4. Type Conversion (Implicit vs. Explicit/Type Casting).
B. Operators
1. Arithmetic Operators (+, -, *, /, %).
2. Relational Operators (==, !=, <, >, <=, >=).
3. Logical Operators (&&, ||, !).
4. Assignment Operators (=, +=, -=, etc.).
5. Bitwise Operators (&, |, ^, ~, <<, >>).
6. Increment/Decrement Operators (++, --).
7. Ternary/Conditional Operator (? :).
8. sizeof Operator.
C. Input/Output (I/O) Operations
1. std::cout for Output.
2. std::cin for Input.
3. std::endl and \n for Newlines.
4. I/O Manipulators (std::fixed, std::setprecision, std::setw).
D. Control Flow Statements
1. Conditional Statements:
a. if, else if, else.
b. switch statement.
2. Looping Statements:
a. for loop.
b. while loop.
c. do-while loop.
3. Jump Statements:
a. break.
b. continue.
c. return.
d. goto (generally discouraged).

III. Functions
A. Introduction to Functions
1. Purpose: Code reusability, modularity.
2. Function Declaration/Prototype.
3. Function Definition.
4. Function Call.
B. Function Parameters
1. Pass by Value.
2. Pass by Reference.
3. Pass by Pointer.
C. Return Values.
D. Function Overloading.
E. Inline Functions.
F. Default Arguments.
G. Recursion.

IV. Arrays and Pointers


A. Arrays
1. Declaration and Initialization.
2. Accessing Elements.
3. Multi-dimensional Arrays.
4. Arrays as Function Arguments.
B. Pointers
1. What are Pointers? Memory addresses.
2. Declaring and Initializing Pointers.
3. Dereferencing Pointers (*).
4. Address-of Operator (&).
5. Pointer Arithmetic.
6. Pointers and Arrays (Array Name as a Pointer).
7. Pointers to Pointers.
8. nullptr (C++11 onward).
C. Dynamic Memory Allocation
1. new operator.
2. delete operator.
3. Memory Leaks.

V. Object-Oriented Programming (OOP) Concepts


A. Introduction to OOP
1. Pillars of OOP: Encapsulation, Abstraction, Inheritance, Polymorphism.
2. Classes and Objects.
B. Classes and Objects
1. Defining a Class.
2. Creating Objects (Instances).
3. Member Variables (Attributes).
4. Member Functions (Methods).
5. Access Specifiers: public, private, protected.
C. Constructors and Destructors
1. Constructors: Special member functions for object initialization.
a. Default Constructor.
b. Parameterized Constructor.
c. Copy Constructor.
2. Destructors: Special member functions for object cleanup.
D. Encapsulation
1. Bundling data and methods that operate on the data.
2. Data Hiding.
3. Getters and Setters.
E. Inheritance
1. Base Class and Derived Class.
2. Types of Inheritance (Single, Multiple, Multilevel, Hierarchical, Hybrid).
3. Access Specifiers in Inheritance.
4. Overriding Base Class Methods.
F. Polymorphism
1. Compile-time Polymorphism (Function Overloading, Operator Overloading).
2. Run-time Polymorphism (Virtual Functions, Pure Virtual Functions, Abstract Classes).
G. Abstraction
1. Hiding implementation details, showing only essential features.
2. Abstract Classes.
3. Interfaces (achieved through pure virtual functions).

VI. Advanced C++ Concepts (Brief Overview)


A. Operator Overloading
1. Overloading Binary and Unary Operators.
2. Friend Functions for Operator Overloading.
B. Friend Functions and Friend Classes
C. Static Members
1. Static Member Variables.
2. Static Member Functions.
D. Templates
1. Function Templates.
2. Class Templates.
3. Generic Programming.
E. Exception Handling
1. try, catch, throw.
2. Handling Errors Gracefully.
F. Standard Template Library (STL)
1. Containers (Vectors, Lists, Deques, Maps, Sets, etc.).
2. Algorithms (Sorting, Searching, etc.).
3. Iterators.
4. Functors (Function Objects).
G. File I/O
1. fstream, ifstream, ofstream.
2. Reading from and Writing to Files.
H. Smart Pointers (C++11 onward)
1. std::unique_ptr.
2. std::shared_ptr.
3. std::weak_ptr.
4. Memory Management and Preventing Leaks.
I. Namespaces
1. Organizing Code.
2. Avoiding Naming Conflicts.
Practice Module 1: Fundamental Concepts of C++

🔹 1. Recursion
✅ What is Recursion?
 Recursion is a process in which a function calls itself.
 It is used to solve problems that can be broken into smaller sub-problems.
✅ Syntax:
returnType functionName(parameters) {
if (base condition)
return result;
else
return recursive call;
}
✅ Example: Factorial using Recursion

✅ Program: Factorial using Recursion


#include <iostream>
using namespace std;

// Recursive function to calculate factorial


int factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1); // Recursive call
}

int main() {
int number;

cout << "Enter a positive integer: ";


cin >> number;

// Error handling for negative input


if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
int result = factorial(number);
cout << "Factorial of " << number << " is: " << result << endl;
}

return 0;
}

📘 Explanation:
🔁 How recursion works (for input 5):
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120

 The function keeps calling itself until it reaches the base case (n == 1).
 Then it returns back through the call stack, multiplying values step by step.

🎯 Sample Output:
Enter a positive integer: 5
Factorial of 5 is: 120

🔹 2. Call by Value and Call by Reference

✅ Call by Value
🔸 Definition:
 A copy of the variable is passed to the function.
 Changes made inside the function do not affect the original value.
🔸 Syntax & Example:
void modify(int x) {
x = x + 5;
}

int main() {
int a = 10;
modify(a);
cout << a; // Output: 10 (no change)
}

✅ Call by Reference
🔸 Definition:
 The original variable is passed using reference (&).
 Changes made inside the function affect the original variable.
🔸 Syntax & Example:
void modify(int &x) {
x = x + 5;
}

int main() {
int a = 10;
modify(a);
cout << a; // Output: 15 (value changed)
}

🧠 Comparison Table:
Feature Call by Value Call by Reference
What is passed? Copy of the value Address/reference
Changes affect main? ❌ No ✅ Yes
Syntax void func(int x) void func(int &x)

✅ Program: Call by Value and Call by Reference


#include <iostream>
using namespace std;
// Function: Call by Value
void callByValue(int x) {
x = x + 10;
cout << "Inside callByValue function, x = " << x << endl;
}

// Function: Call by Reference


void callByReference(int &y) {
y = y + 10;
cout << "Inside callByReference function, y = " << y << endl;
}

int main() {
int a = 5;
int b = 5;

cout << "Before callByValue, a = " << a << endl;


callByValue(a);
cout << "After callByValue, a = " << a << endl;

cout << "\nBefore callByReference, b = " << b << endl;


callByReference(b);
cout << "After callByReference, b = " << b << endl;

return 0;
}

📘 Explanation:
🔹 Call by Value
 Only a copy of the variable is passed to the function.
 Changes inside the function do not affect the original variable.
🔹 Call by Reference
 The actual memory address (reference) is passed to the function.
 Changes inside the function do affect the original variable.

🎯 Sample Output:
Before callByValue, a = 5
Inside callByValue function, x = 15
After callByValue, a = 5

Before callByReference, b = 5
Inside callByReference function, y = 15
After callByReference, b = 15

2. Scope Resolution and Namespaces


 Use global vs local variables, scope resolution operator, custom namespaces.
 Program to demonstrate scope resolution and use of namespaces.
2. Scope Resolution and Namespaces
Scope Resolution Operator (::)
The scope resolution operator (::) is used in C++ to:
 Access global variables when a local variable has the same name.
 Define functions outside the class definition.
 Access static class members.
 Access members of a namespace.
Examples:
1. Global vs Local Variable:
#include <iostream>
int x = 10; // global variable

int main() {
int x = 20; // local variable
std::cout << "Local x: " << x << std::endl;
std::cout << "Global x: " << ::x << std::endl; // scope resolution to access global x
return 0;
}
2. Function Defined Outside the Class:
#include <iostream>
class Test {
public:
void display();
};

void Test::display() {
std::cout << "Hello from Test class!" << std::endl;
}

int main() {
Test t;
t.display(); // Call the member function
return 0;
}

Namespaces
A namespace is used to organize code and avoid naming conflicts in large programs.
Syntax:
namespace MyNamespace {
int value = 42;
void show() {
std::cout << "Value: " << value << std::endl;
}
}
Accessing Namespaces:
1. Using Scope Resolution:
#include <iostream>

// Declare the namespace


namespace MyNamespace {
int value = 42;

void show() {
std::cout << "Value: " << value << std::endl;
}
}

int main() {
std::cout << MyNamespace::value << std::endl;
MyNamespace::show();
return 0;
}
2. Using using Keyword:
#include <iostream>

// Define the namespace first


namespace MyNamespace {
int value = 42;

void show() {
std::cout << "Value from show(): " << value << std::endl;
}
}

// Now bring the namespace into scope


using namespace MyNamespace;

int main() {
std::cout << value << std::endl; // Now value is in scope
show(); // Now show() is in scope
return 0;
}

Standard Namespace (std)


The C++ Standard Library is wrapped in the std namespace.
#include <iostream>
int main() {
std::cout << "Hello World" << std::endl; // using std::
return 0;
}
Or you can write:
using namespace std;

Summary Table:
Feature Description
:: Operator Resolves scope to access global/class/namespace members
Namespace Groups identifiers to avoid name collisions
using namespace Brings all identifiers in a namespace into current scope
std:: Accesses standard library features like cout, endl, etc.

2. (1) Use global vs local variables, scope resolution operator, custom namespaces.
Here's a complete C++ program that demonstrates:
 Global vs Local Variables
 Scope Resolution Operator (::)
 Custom Namespaces

✅ C++ Example: global_local_namespace.cpp


#include <iostream>

// Global variable
int value = 100;

// Custom namespace
namespace MyNamespace {
int value = 200;

void show() {
std::cout << "Namespace value: " << value << std::endl;
}
}

int main() {
int value = 300; // Local variable

std::cout << "Local value: " << value << std::endl; // Local variable
std::cout << "Global value: " << ::value << std::endl; // Scope resolution to
global
std::cout << "Namespace value: " << MyNamespace::value << std::endl; // Access
from namespace

MyNamespace::show(); // Call function inside namespace

return 0;
}

🧠 Output Explanation:
If you run the above code, you’ll get:
Local value: 300
Global value: 100
Namespace value: 200
Namespace value: 200

📌 What This Demonstrates:


Concept Code Used Purpose

Local variable int value = 300; Defined inside main()

int value = 100; (outside


Global variable Accessed using ::value
main)

Namespace
MyNamespace::value Prevents name conflict
variable

Scope resolution ::value and Accesses specific


Concept Code Used Purpose

(::) MyNamespace::show() scopes explicitly

2.(2) Program to demonstrate scope resolution and use of namespaces.

Here is a simple and clear C++ program that demonstrates:

✅ Scope Resolution Operator (::)


✅ Use of Namespaces (including custom namespace)

✅ C++ Program: Demonstrating Scope Resolution and Namespaces

#include <iostream>

// Global variable
int num = 10;

// Custom namespace
namespace MyMath {
int num = 20;

void display() {
std::cout << "Inside namespace MyMath, num = " << num << std::endl;
}
}

int main() {
int num = 30; // Local variable

// Display all three 'num' values


std::cout << "Local num = " << num << std::endl;
std::cout << "Global num = " << ::num << std::endl;
std::cout << "Namespace num = " << MyMath::num << std::endl;
// Call function from namespace
MyMath::display();

return 0;
}

🧾 Output:
Local num = 30
Global num = 10
Namespace num = 20
Inside namespace MyMath, num = 20

📘 Explanation:

Code Meaning
int num = 30; in main() Local variable
::num Scope resolution to access global variable
MyMath::num Accesses variable inside custom namespace
MyMath::display() Calls function defined inside namespace

Experiment 3. Inline Functions


 Definition, syntax, benefits, when not to use.
 Create a program illustrating inline functions.
Here’s a complete explanation and illustration of Inline Functions in C++, covering:
 ✅ Definition
 ✅ Syntax
 ✅ Benefits
 ✅ When not to use
 ✅ Program example

🔹 3. Inline Functions
✅ Definition:
An inline function is a function where the compiler replaces the function call with the
actual function code (body) during compilation, to reduce the overhead of function
calls.
✅ Syntax:
inline return_type function_name(parameters) {
// function body
}
Example:
inline int square(int x) {
return x * x;
}

✅ Benefits of Inline Functions:


1. Reduces function call overhead (especially for small functions).
2. Improves execution speed (for frequently called small functions).
3. Saves the overhead of stack memory operations.
4. Makes code more readable and organized.

❌ When Not to Use Inline Functions:


1. When the function is large or complex.
2. When the function contains:
o Loops (for, while)
o Recursion
o Static variables
o Switch-case statements
3. Inline is only a request to the compiler — it may ignore it.

✅ C++ Program to Illustrate Inline Functions


#include <iostream>
using namespace std;

// Inline function to calculate square of a number


inline int square(int x) {
return x * x;
}
// Inline function to calculate cube
inline int cube(int x) {
return x * x * x;
}

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

cout << "Square of " << num << " is: " << square(num) << endl;
cout << "Cube of " << num << " is: " << cube(num) << endl;

return 0;
}

✅ Output (Sample):
Enter a number: 4
Square of 4 is: 16
Cube of 4 is: 64

Experiment 4:
4. Classes, Objects, and Encapsulation
 Model a Bank Account with data members and functions (deposit, withdraw, display).
 Access Specifiers: Public vs Private – create a sample program.
 this Pointer: Use to resolve naming conflicts.

🔹 4. Classes, Objects, and Encapsulation


Here is a clear and complete explanation of the concept “Classes, Objects, and
Encapsulation” in C++, with syntax and structured examples, as per your request.
✅ 4. Classes, Objects, and Encapsulation

🔹 1. Class and Object – Concept & Syntax


🔸 Class:
A class is a blueprint for creating objects. It contains data members and member
functions.
🔸 Syntax:
class ClassName {
access_specifier:
// data members
// member functions
};
🔸 Example:
class Student {
private:
int rollNo;
string name;

public:
void setDetails(int r, string n) {
rollNo = r;
name = n;
}

void display() {
cout << "Roll No: " << rollNo << ", Name: " << name << endl;
}
};

🔸 Creating Object & Accessing Members


int main() {
Student s1; // Object creation
s1.setDetails(101, "Ravi");
s1.display();
return 0;
}

🔹 2. Encapsulation – Concept
🔸 Definition:
Encapsulation means binding data and related functions into a single unit (class). It also
protects data from unauthorized access.
🔸 Achieved Using:
 private → for data members
 public → for access functions

🔹 3. Bank Account Model – Program


#include <iostream>
using namespace std;

class BankAccount {
private:
int accountNumber;
string holderName;
double balance;

public:
void createAccount(int accNo, string name, double bal) {
accountNumber = accNo;
holderName = name;
balance = bal;
}

void deposit(double amount) {


balance += amount;
cout << "Deposited: " << amount << endl;
}

void withdraw(double amount) {


if (amount > balance)
cout << "Insufficient funds!" << endl;
else {
balance -= amount;
cout << "Withdrawn: " << amount << endl;
}
}

void display() {
cout << "\n--- Account Info ---" << endl;
cout << "Account No: " << accountNumber << endl;
cout << "Holder Name: " << holderName << endl;
cout << "Balance: " << balance << endl;
}
};

int main() {
BankAccount acc;
acc.createAccount(1001, "P. Mohan", 5000.0);
acc.deposit(1500);
acc.withdraw(2000);
acc.display();
return 0;
}

🔹 4. Access Specifiers – public vs private


Access Specifier Meaning
private Accessible only inside the class
public Accessible from outside the class (through object)

🔹 5. this Pointer – Concept & Syntax


🔸 Definition:
The this pointer is an implicit pointer that points to the current calling object inside a class.
🔸 Use Case – Resolving Naming Conflict:
class Student {
private:
int id;
string name;

public:
void setData(int id, string name) {
this->id = id; // resolves conflict
this->name = name;
}

void display() {
cout << "ID: " << id << ", Name: " << name << endl;
}
};
🔸 Syntax:
this->data_member = parameter;

✅ Summary Table
Topic Syntax/Usage Example
Class Declaration class ClassName { ... };
Object Creation ClassName obj;
Access Specifiers private:, public:
Encapsulation Keep data private, use public methods to access
this Pointer this->x = x; to avoid name conflict

5. Function Overloading
 Define multiple functions with same name but different parameters.
 Use of default arguments.
 Friend Function to access private data.
✅ 5. Function Overloading, Default Arguments & Friend Function

🔹 1. Function Overloading
✅ Definition:
Function Overloading means defining multiple functions with the same name but
different number or types of parameters.
✅ Syntax:
return_type function_name(parameter_list);

✅ Example:
#include <iostream>
using namespace std;

class Print {
public:
void show(int x) {
cout << "Integer: " << x << endl;
}

void show(double x) {
cout << "Double: " << x << endl;
}

void show(string x) {
cout << "String: " << x << endl;
}
};

int main() {
Print p;
p.show(5); // Calls int version
p.show(5.5); // Calls double version
p.show("Hello"); // Calls string version
return 0;
}

🔹 2. Default Arguments
✅ Definition:
Default Arguments allow a function to be called with fewer arguments than it is defined
with.
Missing values are filled with default values.
✅ Syntax:
return_type function_name(type1 a = val1, type2 b = val2);
✅ Example:
#include <iostream>
using namespace std;

void greet(string name = "Guest") {


cout << "Hello, " << name << "!" << endl;
}

int main() {
greet(); // Uses default argument "Guest"
greet("Pattabhi"); // Uses provided argument
return 0;
}

🔹 3. Friend Function
✅ Definition:
A friend function is not a member of the class, but it can access private and protected
members of that class.
✅ Syntax:
class ClassName {
friend return_type function_name(arguments);
};

✅ Example:
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box() {
length = 10;
}

// Friend function declaration


friend void displayLength(Box b);
};

// Friend function definition


void displayLength(Box b) {
cout << "Length is: " << b.length << endl; // Accessing private member
}

int main() {
Box b1;
displayLength(b1); // Friend function call
return 0;
}

✅ Summary Table
Concept Purpose Syntax/Usage
Function Same function name, different void show(int); void
Overloading parameters show(double);
Provide default value to function void greet(string name =
Default Arguments
parameters "Guest");
Non-member function accessing friend void displayLength(Box
Friend Function
private data b);

6. Constructors and Destructors


 Create a class demonstrating default constructor and destructor.
 Constructor overloading and copy constructor with examples.
Here's a complete and clear explanation of Constructors and Destructors in C++, including
syntax, examples, and illustrations for:
 ✅ Default Constructor
 ✅ Destructor
 ✅ Constructor Overloading
 ✅ Copy Constructor

✅ 6. Constructors and Destructors

🔹 1. Default Constructor
✅ Definition:
A default constructor is a constructor that takes no parameters. It is automatically called
when an object is created.
✅ Syntax:
class ClassName {
public:
ClassName(); // Default constructor
};

✅ Example:
#include <iostream>
using namespace std;

class Student {
public:
Student() { // Default Constructor
cout << "Default Constructor Called!" << endl;
}
};

int main() {
Student s1; // Constructor is called automatically
return 0;
}
🔹 2. Destructor
✅ Definition:
A destructor is a special member function used to release resources when the object is
destroyed.
✅ Syntax:
~ClassName(); // tilde (~) symbol

✅ Example:
#include <iostream>
using namespace std;

class Student {
public:
Student() {
cout << "Constructor called." << endl;
}

~Student() {
cout << "Destructor called." << endl;
}
};

int main() {
Student s1;
return 0; // Destructor called automatically at end
}

🔹 3. Constructor Overloading
✅ Definition:
Constructor overloading means multiple constructors with the same name (class name),
but different parameter lists.

✅ Example:
#include <iostream>
using namespace std;

class Student {
private:
int rollNo;
string name;

public:
// Default constructor
Student() {
rollNo = 0;
name = "Unknown";
}

// Parameterized constructor
Student(int r, string n) {
rollNo = r;
name = n;
}

void display() {
cout << "Roll No: " << rollNo << ", Name: " << name << endl;
}
};

int main() {
Student s1; // Calls default constructor
Student s2(101, "Ravi"); // Calls parameterized constructor

s1.display();
s2.display();
return 0;
}
🔹 4. Copy Constructor
✅ Definition:
A copy constructor creates a new object by copying the values from an existing object.
✅ Syntax:
ClassName(const ClassName &obj);

✅ Example:
#include <iostream>
using namespace std;

class Student {
private:
int rollNo;

public:
// Parameterized constructor
Student(int r) {
rollNo = r;
}

// Copy constructor
Student(const Student &s) {
rollNo = s.rollNo;
}

void display() {
cout << "Roll No: " << rollNo << endl;
}
};

int main() {
Student s1(101);
Student s2 = s1; // Copy constructor called

s1.display();
s2.display();
return 0;
}

✅ Summary Table
Concept Description Syntax Example
Default Constructor Constructor with no parameters Student() { }
Destructor Destroys object and frees resources ~Student() { }
Constructor Multiple constructors with different Student(); Student(int,
Overloading parameters string);
Copy Constructor Creates a new object from another object Student(const Student &s)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy