2 BytesC++ course_2014_c3_ function basics¶meters and overloadingkinan keshkeh
油
The document discusses functions in C++. It explains that functions can be defined in two ways: with declaration/calling/definition or with just declaration and definition. It provides examples of declaring a function that calculates the average of two numbers, calling that function, and defining the function. It also discusses local and global variables and their scopes. Finally, it lists some common predefined functions in C++ like sqrt, pow, abs, and rand.
Classes allow programmers to create new types that model real-world objects. A class defines both data attributes and built-in operations that can operate on that data. C++ provides built-in classes like string and iostream that add powerful functionality to the language. The string class allows easy storage and manipulation of strings, while the iostream classes (istream and ostream) define objects like cin and cout for input/output. These classes provide many useful built-in operations that make input/output powerful yet easy to use.
The document discusses function overloading in C++ and provides an example program to calculate the area of different shapes using function overloading. It then discusses constructors and destructors with examples and explains polymorphism with an example. Next, it discusses different types of inheritance in C++ and provides an example program to implement operator overloading for a distance class. It also discusses virtual functions with an example and access specifiers in classes. Finally, it provides examples to define a student class, implement quicksort using templates and overloading relational operators.
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
油
Certainly, here's a brief explanation of constructors, destructors, and operator overloading without using code:
Constructors: Constructors are special methods used to initialize objects of a class. They set the initial state of an object when it is created.
Destructors: Destructors are special methods used to clean up resources and perform necessary cleanup when an object is no longer needed or goes out of scope. They ensure proper resource management.
Operator Overloading: Operator overloading is a feature that allows you to define custom behaviors for operators such as +, -, *, /, etc., when they are applied to objects of your class. It enables you to work with objects in a way that is meaningful for your specific class.
Constructors can be of different types:
Default Constructors: Initialize objects with default values.
Parameterized Constructors: Accept arguments to initialize objects with specific values.
Copy Constructors: Create a new object as a copy of an existing object.
Constructor Overloading: A class can have multiple constructors with different parameter lists, providing flexibility in object initialization.
Destructors are executed automatically when an object is destroyed. They are essential for releasing resources like memory, file handles, or network connections, ensuring proper cleanup and preventing resource leaks.
Operator overloading enables you to define how operators work with objects of your class. For instance, you can specify what the + operator does when applied to two objects of your class, allowing for custom operations that make sense in the context of your class's functionality.
In summary, constructors initialize objects, destructors handle cleanup, and operator overloading allows custom operations with operators when working with objects. These features are crucial for building custom classes in object-oriented programming.
This document provides an overview of key concepts in C++ programming including program structure, variables, data types, operators, input/output, control structures, and functions. It discusses the basic building blocks of a C++ program including comments, header files, declaring variables, reading/writing data, and program flow. Control structures like if/else, switch, while, for, break and continue are explained. The document also covers fundamental C++ concepts such as variables, data types, operators, and basic input/output.
The document contains examples demonstrating various object-oriented programming concepts in C++ including constructors, destructors, inheritance, polymorphism, operator overloading, templates, and more. Each example includes the code for a concept, the output of running the code, and a brief description.
This document contains code snippets for 12 common C++ programs: 1) checking if a number is even or odd, 2) swapping two numbers, 3) checking if a year is a leap year, 4) sorting words in dictionary order, 5) calculating a factorial, 6) generating a Fibonacci series, 7) transposing a matrix, 8) using constructors and destructors, 9) demonstrating multiple inheritance, 10) using static members and functions, 11) exception handling, and 12) file input/output. Each code snippet is followed by sample input/output to demonstrate the program's functionality.
1. The document provides an introduction to object-oriented programming concepts and C++ programming.
2. It discusses the need for OOP over procedure-oriented programming and highlights the differences between the two approaches.
3. The document then covers basic C++ concepts like data types, functions, classes, inheritance and polymorphism through examples.
CBSE Question Paper Computer Science with C++ 2011Deepak Singh
油
This document provides instructions for a 3-hour computer science exam with 70 maximum marks. It includes 6 questions with subparts testing various C++ programming concepts. Question 1 covers local vs global variables, header files, error correction, and finding output. Question 2 differentiates class members, illustrates function overloading, and defines a class. Question 3 includes array functions for transferring content between arrays, finding an array element location, and queue operations. Question 4 involves file input/output functions for modifying a data file.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
The document provides an introduction and overview of key C++ concepts such as comments, input/output streams, declarations, data types, reference parameters, const qualifier, default arguments, and function overloading. It describes how each concept works in C++, provides examples, and in some cases compares the concept to how it works in C. The document is aimed at teaching basic C++ concepts.
C++ is an object-oriented programming language that is an extension of C. It was developed in the early 1980s by Bjarne Stroustrup at Bell Labs. C++ supports concepts like inheritance, polymorphism, and encapsulation that make it suitable for large, complex programs. Inheritance allows classes to inherit properties from parent classes. Polymorphism is the ability to process objects of different types in the same way. Encapsulation combines data and functions that operate on that data within a single unit, hiding implementation details. File input/output in C++ can be handled through streams like ifstream for input and ofstream for output.
This document provides an overview of the C++ Data Structures lab manual. It covers topics like C++ review, implementation of various data structures like stack, queue, linked list, binary tree, graph. It also discusses sorting and searching techniques, file input/output, functions, classes, templates and exercises for students to practice implementing different data structures and algorithms. The instructor's contact details are provided at the beginning.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- C++ was developed to include object-oriented features while retaining C's simplicity, with classes, inheritance, and other features enabling abstract data types.
- Key concepts covered include classes, objects, member functions, inline functions, passing objects as parameters, returning objects, arrays of objects, and function overloading. Examples are provided to illustrate each concept.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- Some problems with C include lack of consideration for data elements and lack of security for networks.
- C++ classes contain variables and functions to characterize objects. Data and functions are tied together and data is hidden.
- Key concepts explained include objects, member functions, constructors, destructors, inheritance and polymorphism.
- Examples demonstrate basic C++ programs, classes, objects, arrays of objects, function overloading and the this pointer.
The document outlines a lecture plan for object oriented programming. It covers topics like structures and classes, function overloading, constructors and destructors, operator overloading, inheritance, polymorphism, and file streams. It provides examples to explain concepts like structures, classes, access specifiers, friend functions, and operator overloading. The document also includes questions for students to practice these concepts.
1) A base class pointer can point to a derived class object but cannot access the derived class's additional functions without a cast.
2) Declaring a function as virtual in the base class allows it to be overridden in derived classes and called polymorphically through a base class pointer.
3) A pure virtual function is like an abstract function that derived classes must implement. A class with a pure virtual function is an abstract class that cannot be instantiated.
The document discusses copy constructors in C++. It explains that a copy constructor is used to initialize an object from another object of the same class. It takes the other object as a reference parameter. The document provides an example class with a copy constructor that copies the member variables of one object to another. It also shows sample code that uses the copy constructor to make a copy of an object.
This document contains code snippets for 12 common C++ programs: 1) checking if a number is even or odd, 2) swapping two numbers, 3) checking if a year is a leap year, 4) sorting words in dictionary order, 5) calculating a factorial, 6) generating a Fibonacci series, 7) transposing a matrix, 8) using constructors and destructors, 9) demonstrating multiple inheritance, 10) using static members and functions, 11) exception handling, and 12) file input/output. Each code snippet is followed by sample input/output to demonstrate the program's functionality.
1. The document provides an introduction to object-oriented programming concepts and C++ programming.
2. It discusses the need for OOP over procedure-oriented programming and highlights the differences between the two approaches.
3. The document then covers basic C++ concepts like data types, functions, classes, inheritance and polymorphism through examples.
CBSE Question Paper Computer Science with C++ 2011Deepak Singh
油
This document provides instructions for a 3-hour computer science exam with 70 maximum marks. It includes 6 questions with subparts testing various C++ programming concepts. Question 1 covers local vs global variables, header files, error correction, and finding output. Question 2 differentiates class members, illustrates function overloading, and defines a class. Question 3 includes array functions for transferring content between arrays, finding an array element location, and queue operations. Question 4 involves file input/output functions for modifying a data file.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
The document provides an introduction and overview of key C++ concepts such as comments, input/output streams, declarations, data types, reference parameters, const qualifier, default arguments, and function overloading. It describes how each concept works in C++, provides examples, and in some cases compares the concept to how it works in C. The document is aimed at teaching basic C++ concepts.
C++ is an object-oriented programming language that is an extension of C. It was developed in the early 1980s by Bjarne Stroustrup at Bell Labs. C++ supports concepts like inheritance, polymorphism, and encapsulation that make it suitable for large, complex programs. Inheritance allows classes to inherit properties from parent classes. Polymorphism is the ability to process objects of different types in the same way. Encapsulation combines data and functions that operate on that data within a single unit, hiding implementation details. File input/output in C++ can be handled through streams like ifstream for input and ofstream for output.
This document provides an overview of the C++ Data Structures lab manual. It covers topics like C++ review, implementation of various data structures like stack, queue, linked list, binary tree, graph. It also discusses sorting and searching techniques, file input/output, functions, classes, templates and exercises for students to practice implementing different data structures and algorithms. The instructor's contact details are provided at the beginning.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- C++ was developed to include object-oriented features while retaining C's simplicity, with classes, inheritance, and other features enabling abstract data types.
- Key concepts covered include classes, objects, member functions, inline functions, passing objects as parameters, returning objects, arrays of objects, and function overloading. Examples are provided to illustrate each concept.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- Some problems with C include lack of consideration for data elements and lack of security for networks.
- C++ classes contain variables and functions to characterize objects. Data and functions are tied together and data is hidden.
- Key concepts explained include objects, member functions, constructors, destructors, inheritance and polymorphism.
- Examples demonstrate basic C++ programs, classes, objects, arrays of objects, function overloading and the this pointer.
The document outlines a lecture plan for object oriented programming. It covers topics like structures and classes, function overloading, constructors and destructors, operator overloading, inheritance, polymorphism, and file streams. It provides examples to explain concepts like structures, classes, access specifiers, friend functions, and operator overloading. The document also includes questions for students to practice these concepts.
1) A base class pointer can point to a derived class object but cannot access the derived class's additional functions without a cast.
2) Declaring a function as virtual in the base class allows it to be overridden in derived classes and called polymorphically through a base class pointer.
3) A pure virtual function is like an abstract function that derived classes must implement. A class with a pure virtual function is an abstract class that cannot be instantiated.
The document discusses copy constructors in C++. It explains that a copy constructor is used to initialize an object from another object of the same class. It takes the other object as a reference parameter. The document provides an example class with a copy constructor that copies the member variables of one object to another. It also shows sample code that uses the copy constructor to make a copy of an object.
艶COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page
Updating drivers is usually an initial step to avoid hardware failure, system instability, and hidden security vulnerabilities. Update drivers regularly is also an effective way to enhance your overall PC performance and maximize your gaming experience.
Based on the cloud library, IObit Driver Booster Pro can always be the first to identify outdated drivers and download and update drivers at an unrivaled speed. The backup feature is an easy, effective, and risk-free solution to keeping your drivers up to date.
艶COPY LINK & PASTE ON GOOGLE https://filmoracrack.info//after-verification-click-go-to-download-page/
Revo Uninstaller Pro is innovative uninstaller program which helps you to uninstall unnecessary software and remove easily unwanted programs installed on your
The Evolution of Microsoft Project Portfolio ManagementOnePlan Solutions
油
Project portfolio management has come a long way but many PMOs are still stuck using static plans, siloed tools, and processes that dont reflect how work actually gets done today. As business priorities shift faster and teams grow more dispersed, PMOs must evolve from project trackers to strategic enablers. That means leading with visibility, agility, and real-time insight, not just governance.
In this webinar, well take a closer look at how Microsoft Project Portfolio Management is evolving and how the most effective PMOs are adapting. Youll see how OnePlan helps bring strategy and execution together in Microsoft 365, giving you a more connected, modern approach to managing portfolios.
Java and AI with LangChain4j: Jakarta EE gets AIEdward Burns
油
Generative AI burst on to the public scene in November 2022, over ten years after Andrew Ngs Machine Learning premiered on Coursera. Java developers have long felt like second class citizens, compared to the cool Python kids. LangChain4J changes the game. Java is cool with AI now! This lecture from 30-year industry veteran Ed Burns explores why it took so long for Java developers to have access to easy-to-use AI libraries, compared to Python developers. LangChain4J is the most popular of the Java libraries, but others exist. After a brief look at the landscape, well take a deeper look at LangChain4J and how you use it to perform the most popular AI usage pattern: Retrieval Augmented Generation (RAG). RAG is basically a way to bring your own domain specific data to an existing AI model, and benefit from its power.
Imagine a world where you can respond instantly to any customer, anytime, anywhere.
Improve user satisfaction on every channel. With Jotform AI Agents, you can streamline your customer service processes. Easily train your agent with your company data, identify the common questions you receive and your answers. Let your agent handle the rest.
Learn more about the benefits of Jotform AI Agents with this slide. For more information, visit https://www.jotform.com/ai/agents/
艶COPY LINK & PASTE ON GOOGLEhttps://up-community.wiki/ds/
Wondershare Dr.Fone Crack is a comprehensive mobile phone management and recovery software designed to help users recover lost data, repair system issues, and manage mobile devices. It supports both Android and iOS platforms, offering a wide range of features aimed at restoring files, repairing software problems, and backing up or transferring data.
Movavi Video Editor Crack + Activation Key [2025]l07307095
油
COPY & PASTE LINK
https://upcommunity.net/dl/
Movavi Video Editor is a beginner-friendly multimedia application that can help you create professional-level videos.
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odooAxisTechnolabs
油
Tour, Travel and Hotel booking management module in odoo
Tour Booking, Booking Service, Tour Agents, Hotel Booking in odoo
Visit And Buy Now : https://bit.ly/3THskJQ
Tour and Travel Management odoo module helps to manage contracts with all your suppliers with your accommodation, transportation, restaurants, guides and other logistical requirements.
Lets checkout some Amazing Key Features for Tour and Travel Booking Management in odoo:
Key Features :
Tour Management Dashboard
Tour Itinerary
Tour Consulting
Booking Services
Hotel Room Type
And much more...
Just visit our app link to know more exciting features of tour and travel management odoo module :
Want to Download ?
Odoo18 : https://bit.ly/3ULBe90
Odoo17 : https://bit.ly/3THskJQ
Odoo 16 : https://bit.ly/3Vx1KRe
Odoo 15 : https://bit.ly/3tZ53qj
Odoo 14 : https://bit.ly/3nEvL39
Odoo 13 : https://bit.ly/3nKZFTx
Odoo 12 : https://bit.ly/32fZN5W
Odoo 11 : https://bit.ly/3rtiJ9O
¥Explore more our Apps : https://bit.ly/3oFIOCF
¥Want A demo ? business@axistechnolabs.com
¥Click here And explore "Axistechnolabs" : https://www.axistechnolabs.com/
¥Contact us : 091066 49361
AR/VR Company in India Simulanis is revolutionizing industries with its cutting-edge Augmented Reality (AR) and Virtual Reality (VR) solutions. This PPT highlights how Simulanis enhances training, simulations, and industrial applications, helping businesses improve efficiency, safety, and workforce development
Parallels Desktop full version o艶COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-pagefflininstaller for macOS. It runs Windows and Mac applications side by side.It allows you to run Windows and Mac applications side by side. Choose your view to make Windows invisible while still using its applications, or keep your Mac's familiar Windows background and controls.
Choreo - The AI-Native Internal Developer Platform as a Service: OverviewWSO2
油
This deck takes you through the need for an internal developer platform and introduces Choreo which provides platform and software engineers with an as a service solution to deliver applications faster and at scale.
艶COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page
Free download Autodesk MotionBuilder for Windows. It is 3D character animation software for virtual production that helps you manipulate and refine data with excellent reliability and efficiency. Capture, edit, and playback complex character animation in a highly responsive, interactive environment and work with a display optimized for both animators and directors.
Wondershare DemoCreator is a screen recording and video editing software designed for creating tutorials, gameplay videos, presentations, and online courses. It combines screen capture with basic video editing tools, making it useful for educators, gamers, and professionals.
https://up-community.wiki/ds/
Building a personal or business website doesn't have to be difficult or expensive. This detailed presentation will teach you how to create a stunning, professional-looking website without any coding skills using beginner-friendly platforms like WordPress, Wix, or Squarespace. Perfect for freelancers, entrepreneurs, students, or content creators, this guide covers everything from selecting a domain name to designing a visually appealing layout, creating key pages (About, Services, Contact), and optimizing for SEO. No tech skills requiredjust follow the steps and launch your website today!
艶COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page
Wondershare Dr.Fone Crack is a comprehensive mobile phone management and recovery software designed to help users recover lost data, repair system issues, and manage mobile devices. It supports both Android and iOS platforms, offering a wide range of features aimed at restoring files, repairing software problems, and backing up or transferring data.
TVersity Pro Media Server Free CRACK Downloadmohsinrazakpa43
油
艶COPY LINK & PASTE ON GOOGLE https://9to5mac.org/after-verification-click-go-to-download-page
TVersity Pro Media Server CRACK is an awesome application that has been developed which will help you detect and share multimedia files on the Internet. With this stellar application you can play as well as record online audio/video content.
2. };
int main() {
Employee emp;
emp.getData();
emp.displayData();
return 0;
}
Explanation:
1. #include <iostream> and #include <string>:
o Includes libraries for input/output operations (cin, cout) and
string handling (string).
2. using namespace std;:
o Avoids the need to prefix standard functions (e.g., std::cin).
3. class Employee:
o Defines a class Employee with private and public members.
o Private Members:
empNo: Employee number.
empName: Employee name.
basic, da, it, netSalary: Basic salary, Dearness Allowance,
Income Tax, and Net Salary, respectively.
o Public Members:
void getData():
Prompts the user to input employee details.
Calculates:
da as 52% of basic.
it as 30% of the sum of basic and da.
netSalary as basic + da - it.
void displayData():
Displays the employee details, including computed
values (da, it, netSalary).
4. int main():
o Creates an object emp of the Employee class.
o Calls getData() to input details and displayData() to display the
results.
Program 2: Constructor Overloading
cpp
Copy code
#include <iostream>
4. cout << "Three Parameters: ";
b3.display();
return 0;
}
Explanation:
1. #include <iostream> and using namespace std;:
o Includes the library for input/output operations and uses the
standard namespace.
2. class Box:
o Defines a class to represent a 3D box with private data
members (length, width, height) and public methods.
o Constructors:
Default Constructor:
Initializes all dimensions (length, width, height) to
zero.
Single Parameter Constructor:
Initializes all dimensions to the same value (l).
Parameterized Constructor:
Initializes dimensions to specified values (l, w, h).
o Public Methods:
double volume():
Returns the volume of the box (length * width *
height).
void display():
Prints the calculated volume of the box.
3. int main():
o Creates three objects of Box:
b1 using the default constructor.
b2 using the single-parameter constructor.
b3 using the three-parameter constructor.
o Calls the display() method for each object to show the volume.
Program 3: Multilevel Inheritance
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
5. protected:
string species;
public:
void setSpecies(string s) {
species = s;
}
};
class Mammal : public Animal {
protected:
int legs;
public:
void setLegs(int l) {
legs = l;
}
};
class Dog : public Mammal {
private:
string breed;
public:
void setBreed(string b) {
breed = b;
}
void display() {
cout << "Species: " << species << endl;
cout << "Legs: " << legs << endl;
cout << "Breed: " << breed << endl;
}
};
int main() {
Dog dog;
dog.setSpecies("Canis");
dog.setLegs(4);
6. dog.setBreed("Labrador");
dog.display();
return 0;
}
Explanation:
1. #include <iostream> and using namespace std;:
o Includes the library for input/output operations and uses the
standard namespace.
2. Multilevel Inheritance:
o class Animal:
The base class with a protected member (species) and a
public method to set its value (setSpecies).
o class Mammal : public Animal:
Inherits Animal and adds a protected member (legs) and a
method to set its value (setLegs).
o class Dog : public Mammal:
Inherits Mammal and adds a private member (breed) and
a method to set its value (setBreed).
void display():
Displays the species, legs, and breed values.
3. int main():
o Creates an object dog of class Dog.
o Calls setSpecies, setLegs, and setBreed to set values for species,
number of legs, and breed.
o Calls display() to print the details.
Program 4: Array of Class Objects
cpp
Copy code
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int rollNo;
char grade;
public:
void getData() {
7. cout << "Enter Name: ";
cin.ignore();
getline(cin, name);
cout << "Enter Roll Number: ";
cin >> rollNo;
cout << "Enter Grade: ";
cin >> grade;
}
void display() {
cout << "nName: " << name;
cout << "nRoll Number: " << rollNo;
cout << "nGrade: " << grade << endl;
}
};
int main() {
Student students[3];
for(int i = 0; i < 3; i++) {
cout << "nEnter details for student " << i+1 <<
":n";
students[i].getData();
}
cout << "nStudent Details:n";
for(int i = 0; i < 3; i++) {
students[i].display();
}
return 0;
}
Explanation:
1. #include <iostream> and #include <string>:
o Includes libraries for input/output operations and string
handling.
2. class Student:
o Represents a student with private data members (name, rollNo,
grade) and public methods.
o Public Methods:
8. void getData():
Prompts the user to input a students details and
stores them in private members.
void display():
Prints the stored student details.
3. int main():
o Creates an array students of size 3 to store details of three
students.
o Input Loop:
Iterates over the array, calling getData() for each student.
o Output Loop:
Iterates over the array, calling display() for each student
to print their details.
Program 5: Function Overloading for Shapes
cpp
Copy code
#include <iostream>
using namespace std;
class Shape {
public:
double perimeter(double radius) {
return 2 * 3.14159 * radius;
}
double perimeter(double length, double width) {
return 2 * (length + width);
}
double perimeter(double a, double b, double c) {
return a + b + c;
}
};
int main() {
Shape shape;
cout << "Circle Perimeter: " << shape.perimeter(5) <<
endl;
cout << "Rectangle Perimeter: " << shape.perimeter(4, 6)
<< endl;
9. cout << "Triangle Perimeter: " << shape.perimeter(3, 4, 5)
<< endl;
return 0;
}
Explanation:
1. #include <iostream> and using namespace std;:
o Includes the library for input/output operations and uses the
standard namespace.
2. class Shape:
o Represents a shape and contains three overloaded methods for
calculating the perimeter of different shapes.
o Method Overloading:
perimeter(double radius): Calculates the perimeter of a
circle (2 * * radius).
perimeter(double length, double width): Calculates the
perimeter of a rectangle (2 * (length + width)).
perimeter(double a, double b, double c): Calculates the
perimeter of a triangle (a + b + c).
3. int main():
o Creates an object shape of the Shape class.
o Calls each of the overloaded perimeter() methods to calculate
and display the perimeter of a circle, rectangle, and triangle.
Program 6: Constructor with Default Arguments
cpp
Copy code
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
Rectangle(double l = 1, double w = 1) {
length = l;
width = w;
}
void display() {
10. cout << "Length: " << length << ", Width: " <<
width << endl;
cout << "Area: " << length * width << endl;
}
};
int main() {
Rectangle r1;
Rectangle r2(5);
Rectangle r3(5, 10);
cout << "Default values: ";
r1.display();
cout << "One argument: ";
r2.display();
cout << "Two arguments: ";
r3.display();
return 0;
}
Explanation:
1. #include <iostream> and using namespace std;:
o Includes the input/output library for cin and cout operations.
2. class Rectangle:
o Represents a rectangle with private data members (length,
width).
o Constructor:
The constructor accepts two arguments (l and w) with
default values (1), meaning if no arguments are passed,
both length and width will be initialized to 1.
o void display():
Displays the dimensions (length, width) and the area
(length * width) of the rectangle.
3. int main():
o Creates three objects of the Rectangle class:
r1 uses the default constructor with no arguments.
r2 uses the constructor with one argument (5 for both
length and width).
r3 uses the constructor with two arguments (5 and 10).
o Calls display() for each object to show their details.
12. void showBalance() {
cout << "Current balance: " << balance << endl;
}
};
int main() {
Account acc(1000);
acc.showBalance();
acc.deposit(500);
acc.withdraw(200);
acc.computeInterest();
acc.showBalance();
return 0;
}
Explanation:
1. #include <iostream> and using namespace std;:
o Includes input/output functionality and the standard
namespace.
2. class Account:
o Represents a bank account with private members (balance and
interestRate).
o Constructor:
Initializes balance with a default value of 0 and
interestRate with 0.05 (5%).
o Methods:
void deposit(double amount):
Deposits a positive amount into the account and
displays the deposited amount.
void withdraw(double amount):
Withdraws an amount if sufficient balance is
available. Displays an error message if insufficient
funds.
void computeInterest():
Computes and adds interest to the balance based
on interestRate.
void showBalance():
Displays the current balance.
3. int main():
o Creates an Account object acc with an initial balance of 1000.
o Calls methods to deposit, withdraw, compute interest, and
display the balance.
13. Program 8: Virtual Functions
cpp
Copy code
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout << "Base class display" << endl;
}
virtual void show() {
cout << "Base class show" << endl;
}
};
class Derived : public Base {
public:
void display() override {
cout << "Derived class display" << endl;
}
void show() override {
cout << "Derived class show" << endl;
}
};
int main() {
Base* base;
Derived derived;
base = &derived;
base->display();
base->show();
return 0;
}
Explanation:
14. 1. #include <iostream> and using namespace std;:
o Includes the standard library for input/output operations.
2. class Base:
o Defines a base class with two virtual methods:
virtual void display():
A virtual method that can be overridden by derived
classes.
virtual void show():
Another virtual method.
3. class Derived : public Base:
o Inherits from Base and overrides both virtual methods.
o void display():
Overridden method in the derived class.
o void show():
Overridden method in the derived class.
4. int main():
o Creates a pointer base of type Base and an object derived of
type Derived.
o base = &derived;:
The base pointer points to the derived object,
demonstrating polymorphism.
o Calls base->display() and base->show(), which invoke the
overridden methods in the Derived class due to virtual
functions.
5. Polymorphism:
o The use of virtual functions allows the derived class methods to
be called through a base class pointer, ensuring dynamic
dispatch.
Program 9: Friend Function
cpp
Copy code
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) {
15. real = r;
imag = i;
}
friend Complex addComplex(Complex c1, Complex c2);
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
Complex addComplex(Complex c1, Complex c2) {
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
int main() {
Complex c1(3, 4), c2(5, 6);
Complex sum = addComplex(c1, c2);
cout << "First complex number: ";
c1.display();
cout << "Second complex number: ";
c2.display();
cout << "Sum: ";
sum.display();
return 0;
}
Explanation:
1. #include <iostream> and using namespace std;:
o Includes the necessary libraries for input/output operations.
2. class Complex:
o Represents a complex number with private members real and
imag.
o Constructor:
Initializes the complex number with default values (0 for
both real and imag).
16. o Friend Function:
friend Complex addComplex(Complex c1, Complex c2):
This function is declared as a friend of the Complex
class, allowing it to access private members (real
and imag) directly.
void display():
Displays the complex number in the form real +
imag i.
3. Complex addComplex(Complex c1, Complex c2):
o Adds two complex numbers by adding their real and imaginary
parts separately.
4. int main():
o Creates two complex numbers c1 and c2.
o Uses the addComplex function to compute their sum and
displays the results.
Program 10: File Handling
cpp
Copy code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream outFile("sample.txt");
if(outFile.is_open()) {
outFile << "This is a line written to the file.n";
outFile << "This is another line.n";
outFile << "Adding some numbers: " << 42 << endl;
outFile.close();
cout << "File created and content written
successfully." << endl;
} else {
cout << "Unable to open file." << endl;
}
ifstream inFile("sample.txt");
string line;
17. cout << "nReading file contents:n";
if(inFile.is_open()) {
while(getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
return 0;
}
Explanation:
1. #include <iostream>, #include <fstream>, and #include <string>:
o Includes the libraries for input/output operations, file handling
(fstream), and string manipulation.
2. ofstream outFile("sample.txt");:
o Creates an ofstream object to write data to a file named
sample.txt.
o if(outFile.is_open()):
Checks if the file is successfully opened. If true, writes
lines to the file and closes it.
3. ifstream inFile("sample.txt");:
o Creates an ifstream object to read data from the file sample.txt.
o while(getline(inFile, line)):
Reads the file line by line and prints each line.
4. File Operations:
o If the file cannot be opened, an error message is printed.
o After reading, the file is closed.