The document discusses various concepts related to functions and operator overloading in C++, including:
1. It describes how functions can be divided into smaller modules to more easily design, build, debug, extend, modify, understand, reuse, and organize large programs.
2. It explains that C++ supports defining multiple functions with the same name but different argument lists through function overloading.
3. It provides examples of overloading operators like +, -, <, <=, assignment (=), increment (++), and decrement (--) operators for user-defined classes.
Operator overloading in C++ allows operators to be redefined for user-defined types like classes. It simplifies writing expressions involving user-defined types. Operators can be overloaded as non-static member functions or global functions. Common operators like +, -, *, / can be overloaded to work with custom classes, allowing expressions like complex_number1 + complex_number2. Stream insertion and extraction operators << and >> are typically overloaded as global functions.
Operator overloading allows operators like + and - to be used with user-defined types in C++. Certain operators like = and [] must be overloaded as member functions, while others like friends and non-members can also be overloaded. Unary operators operate on a single operand, while binary operators require two operands. Overloaded operators are implemented via member functions, non-member functions, or friend functions depending on whether the left operand is of the class type. Strings can also be manipulated using overloaded operators by defining a string class with a character pointer and length.
The term overloading means ‘providing multiple definitions of’. Overloading of functions involves defining distinct functions which share the same name, each of which has a unique signature. Function overloading is appropriate for:
Defining functions which essentially do the same thing, but operate on different data types.
Providing alternate interfaces to the same function.
Function overloading is purely a programming convenience.
Operators are similar to functions in that they take operands (arguments) and return a value. Most of the built-in C++ operators are already overloaded. For example, the + operator can be used to add two integers, two reals, or two addresses. Therefore, it has multiple definitions. The built-in definitions of the operators are restricted to built-in types. Additional definitions can be provided by the programmer so that they can also operate on user-defined types. Each additional definition is implemented by a function.
This document discusses operator overloading in C++. It begins by defining operator overloading as giving special meanings to operators for user-defined data types. It then covers overloading unary and binary operators using member functions and friend functions. Some key points include: only existing operators can be overloaded, binary operators take operands as arguments, and type conversions between basic and user-defined types require custom conversion routines like constructors or casting functions. The document also provides examples of overloading operators for complex numbers and strings.
Operator overloading allows operators like +, -, *, etc. to be redefined to work on user-defined types like classes. This is done by defining member functions for the operators. For example, to overload + to add two Distance objects, a member function Distance operator+(Distance) would be defined. Overloading operators allows user-defined types to be used in expressions like built-in types for a more natural interface. Some common operators that can be overloaded include arithmetic, relational, logical, and assignment operators. There are some restrictions like not changing operator precedence or number of operands.
The document discusses inline functions in C++. Inline functions allow code from a function to be pasted directly into the call site rather than executing a function call. This avoids overhead from calling and returning from functions. Good candidates for inline are small, simple functions called frequently. The document provides an example of a function defined with the inline keyword and the optimizations a compiler may perform after inlining. It also compares inline functions to macros and discusses where inline functions are best used.
This document discusses operator overloading in C++. It covers introducing operator overloading, the 'this' pointer, syntax of operator overloading, restrictions on operator overloading, implementing operator overloading as member and non-member functions, overloading unary and binary operators, overloading relational operators, and data conversion. Examples are provided to demonstrate overloading operators like +, -, <, and implementing them as member and non-member functions.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
6. Functions in C ++ programming object oriented programmingAhmad177077
In C++, functions are used to organize code into modular blocks that can perform specific tasks. Functions allow you to avoid code repetition, improve code readability, and make your program more manageable.
Operator overloading allows operators like + and - to have different implementations depending on the types of their operands. It allows user-defined types to be manipulated using the same syntax as built-in types. The document discusses various aspects of operator overloading like overloading unary, binary, and stream insertion/extraction operators. It also covers type conversions between basic and user-defined types using constructors and conversion functions. Restrictions on which operators can be overloaded and how different conversion scenarios are handled are explained.
Operator overloading allows operators like + and - to be used with custom class and struct types by defining them as methods. It overloads their original meaning for built-in types while retaining that functionality. Binary operators take two parameters while unary operators take one. Overloading improves code readability and makes operations on custom types look more natural. However, overloading is limited to certain predefined operators and cannot change properties like precedence.
Operator overloading allows operators like + and << to be used with user-defined types by defining corresponding member functions. For example, the + operator can be overloaded to add two Distance objects by defining the member function operator+. This makes code more readable compared to explicit function calls. Overloading unary operators like ++ requires defining operator++(), while overloading binary operators like + requires defining both operator+() and operator+=(). The return type and arguments of overloaded operators must match the conventional operator.
The document discusses operator overloading in C++. It defines operator overloading as giving normal C++ operators like +, -, etc. additional meanings when applied to user-defined data types. It categorizes operators as unary and binary. It lists the operators that can and cannot be overloaded and provides examples of overloading unary, binary, and assignment operators. The document also discusses automatic and user-defined type conversion between basic and user-defined types.
The document is the course syllabus for C++ subject in the 2nd semester of B Sc IT program. It lists the following key topics to be covered: Function overloading, Operator overloading, Inheritance, Different forms of inheritance, Constructors and Destructors in inheritance, Virtual base class, Pointer to base class, Dynamic polymorphism, Virtual functions, Type conversions.
Operator Overloading
The keyword Operator
Overloading Unary Operator
Operator Return Type
Overloading Assignment Operator (=)
Rules for Overloading Operators
Inheritance
Reusability
Types of Inheritance
Virtual Base Classes
Object as a Class Member
Abstract Classes
Advantages of Inheritance
Disadvantages of Inheritance
Operator overloading allows functions and operators to be defined for user-defined types. This customizes the behavior of operators for new types. The lecture discusses unary operators like prefix and postfix ++ and --, binary operators like + and <, and which operators cannot be overloaded. It also covers automatic type conversion between basic types and user-defined conversion between types using cast operators.
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.
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.
Operator overloading allows user-defined types in C++ to behave similarly to built-in types when operators are used on them. It allows operators to have special meanings depending on the context. Some key points made in the document include:
- Operator overloading enhances the extensibility of C++ by allowing user-defined types to work with operators like addition, subtraction, etc.
- Common operators that can be overloaded include arithmetic operators, increment/decrement, input/output, function call, and subscript operators.
- To overload an operator, a member or friend function is declared with the same name as the operator being overloaded. This function performs the desired operation on the class type.
-
This document discusses object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, and abstract classes. It covers topics such as function overloading, operator overloading, virtual base classes, virtual functions, and pure virtual functions. It provides examples of overloading unary and binary operators using member functions and friend functions. It also explains the differences between virtual functions and pure virtual functions, and how abstract classes are used with pure virtual functions.
The document discusses inline functions in C++. Inline functions allow code from a function to be pasted directly into the call site rather than executing a function call. This avoids overhead from calling and returning from functions. Good candidates for inline are small, simple functions called frequently. The document provides an example of a function defined with the inline keyword and the optimizations a compiler may perform after inlining. It also compares inline functions to macros and discusses where inline functions are best used.
This document discusses operator overloading in C++. It covers introducing operator overloading, the 'this' pointer, syntax of operator overloading, restrictions on operator overloading, implementing operator overloading as member and non-member functions, overloading unary and binary operators, overloading relational operators, and data conversion. Examples are provided to demonstrate overloading operators like +, -, <, and implementing them as member and non-member functions.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
6. Functions in C ++ programming object oriented programmingAhmad177077
In C++, functions are used to organize code into modular blocks that can perform specific tasks. Functions allow you to avoid code repetition, improve code readability, and make your program more manageable.
Operator overloading allows operators like + and - to have different implementations depending on the types of their operands. It allows user-defined types to be manipulated using the same syntax as built-in types. The document discusses various aspects of operator overloading like overloading unary, binary, and stream insertion/extraction operators. It also covers type conversions between basic and user-defined types using constructors and conversion functions. Restrictions on which operators can be overloaded and how different conversion scenarios are handled are explained.
Operator overloading allows operators like + and - to be used with custom class and struct types by defining them as methods. It overloads their original meaning for built-in types while retaining that functionality. Binary operators take two parameters while unary operators take one. Overloading improves code readability and makes operations on custom types look more natural. However, overloading is limited to certain predefined operators and cannot change properties like precedence.
Operator overloading allows operators like + and << to be used with user-defined types by defining corresponding member functions. For example, the + operator can be overloaded to add two Distance objects by defining the member function operator+. This makes code more readable compared to explicit function calls. Overloading unary operators like ++ requires defining operator++(), while overloading binary operators like + requires defining both operator+() and operator+=(). The return type and arguments of overloaded operators must match the conventional operator.
The document discusses operator overloading in C++. It defines operator overloading as giving normal C++ operators like +, -, etc. additional meanings when applied to user-defined data types. It categorizes operators as unary and binary. It lists the operators that can and cannot be overloaded and provides examples of overloading unary, binary, and assignment operators. The document also discusses automatic and user-defined type conversion between basic and user-defined types.
The document is the course syllabus for C++ subject in the 2nd semester of B Sc IT program. It lists the following key topics to be covered: Function overloading, Operator overloading, Inheritance, Different forms of inheritance, Constructors and Destructors in inheritance, Virtual base class, Pointer to base class, Dynamic polymorphism, Virtual functions, Type conversions.
Operator Overloading
The keyword Operator
Overloading Unary Operator
Operator Return Type
Overloading Assignment Operator (=)
Rules for Overloading Operators
Inheritance
Reusability
Types of Inheritance
Virtual Base Classes
Object as a Class Member
Abstract Classes
Advantages of Inheritance
Disadvantages of Inheritance
Operator overloading allows functions and operators to be defined for user-defined types. This customizes the behavior of operators for new types. The lecture discusses unary operators like prefix and postfix ++ and --, binary operators like + and <, and which operators cannot be overloaded. It also covers automatic type conversion between basic types and user-defined conversion between types using cast operators.
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.
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.
Operator overloading allows user-defined types in C++ to behave similarly to built-in types when operators are used on them. It allows operators to have special meanings depending on the context. Some key points made in the document include:
- Operator overloading enhances the extensibility of C++ by allowing user-defined types to work with operators like addition, subtraction, etc.
- Common operators that can be overloaded include arithmetic operators, increment/decrement, input/output, function call, and subscript operators.
- To overload an operator, a member or friend function is declared with the same name as the operator being overloaded. This function performs the desired operation on the class type.
-
This document discusses object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, and abstract classes. It covers topics such as function overloading, operator overloading, virtual base classes, virtual functions, and pure virtual functions. It provides examples of overloading unary and binary operators using member functions and friend functions. It also explains the differences between virtual functions and pure virtual functions, and how abstract classes are used with pure virtual functions.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Passenger car unit (PCU) of a vehicle type depends on vehicular characteristics, stream characteristics, roadway characteristics, environmental factors, climate conditions and control conditions. Keeping in view various factors affecting PCU, a model was developed taking a volume to capacity ratio and percentage share of particular vehicle type as independent parameters. A microscopic traffic simulation model VISSIM has been used in present study for generating traffic flow data which some time very difficult to obtain from field survey. A comparison study was carried out with the purpose of verifying when the adaptive neuro-fuzzy inference system (ANFIS), artificial neural network (ANN) and multiple linear regression (MLR) models are appropriate for prediction of PCUs of different vehicle types. From the results observed that ANFIS model estimates were closer to the corresponding simulated PCU values compared to MLR and ANN models. It is concluded that the ANFIS model showed greater potential in predicting PCUs from v/c ratio and proportional share for all type of vehicles whereas MLR and ANN models did not perform well.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
☁️ GDG Cloud Munich: Build With AI Workshop - Introduction to Vertex AI! ☁️
Join us for an exciting #BuildWithAi workshop on the 28th of April, 2025 at the Google Office in Munich!
Dive into the world of AI with our "Introduction to Vertex AI" session, presented by Google Cloud expert Randy Gupta.
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
its all about Artificial Intelligence(Ai) and Machine Learning and not on advanced level you can study before the exam or can check for some information on Ai for project
new ppt artificial intelligence historyyyPianoPianist
Ad
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
1. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 1
SHRI SHANKARACHARYA TECHNICAL CAMPUS
UNIT IV
Operator Overloading
Operator overloading is a feature in C++ that allows developers to redefine the behavior of
operators for user-defined types, such as classes. This means you can make objects of your
classes respond to operators like +, -, ==, and even << in custom ways, similar to how built-
in data types behave.
Why Use Operator Overloading?
1. Intuitive Code: With operator overloading, you can write code that’s more readable
and closer to natural language, which is especially useful in cases where you’re
dealing with mathematical or logical objects.
2. Consistency: Overloading makes using custom data types feel consistent with using
built-in types, which can reduce errors and make the code easier to understand and
maintain.
3. Encapsulation: By embedding operator functionality within classes, you keep
operations related to a specific data type encapsulated, following object-oriented
principles.
Basic Concepts and Rules of Operator Overloading
1. Operators that can be Overloaded:
o Almost all operators can be overloaded, including arithmetic (+, -, *, /),
relational (==, !=, <, >), assignment (=), and stream (<<, >>) operators.
o Some operators, however, cannot be overloaded. These include:
▪ . (member access)
▪ .* (pointer-to-member access)
▪ :: (scope resolution)
▪ ?: (ternary conditional)
▪ sizeof (object size calculation)
2. Syntax of Operator Overloading:
o Operator overloading is done by defining a special function using the operator
keyword followed by the operator symbol, for example: operator+,
operator==, etc.
o Overloaded operators can be implemented as either member functions or
friend functions.
3. Operator Overloading with Member Functions vs. Friend Functions:
o Member functions: The left operand must be an object of the class. For
example, to overload + as a member function, you might write:
2. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 2
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Complex operator+(const Complex& other) const;
o Friend functions: These can be used if the left operand is not an object of the
class (e.g., a built-in type). Friend functions allow more flexibility in operator
overloading.
4. Overloading Unary and Binary Operators:
o Unary Operators: Operators like +, -, ++, and -- that operate on a single
operand can be overloaded with one argument (if defined outside the class) or
no arguments (if defined inside the class).
o Binary Operators: Operators like +, -, *, /, and == that operate on two
operands can be overloaded with two arguments (if defined outside the class)
or one argument (if defined inside the class).
5. Rules and Limitations:
o Precedence and Associativity: Overloading does not change the precedence or
associativity of operators.
o Operator Overloading Does Not Alter Default Behavior: You cannot create
new operators or change the fundamental behavior of operators, such as the
number of operands.
o Return Types: The return type of an overloaded operator function should
match the operation it represents. For example, an overloaded + operator
usually returns a new object of the same type as the class.
Overloading Various Operators
Overloading the + Operator for a Complex Number Class
The + operator is overloaded to add two complex numbers by adding their real and imaginary
parts separately.
#include <iostream>
using namespace std;
class Complex {
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
3. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 3
SHRI SHANKARACHARYA TECHNICAL CAMPUS
// Overload the '+' operator
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.5, 2.5), c2(1.5, 4.0);
Complex c3 = c1 + c2; // Uses overloaded '+' operator
c3.display(); // Output: 5 + 6.5i
}
the + operator is overloaded to add the real and imag parts of Complex numbers. This makes
adding complex numbers as intuitive as adding primitive types.
Overloading the - Operator for a Vector Class
Here, we overload the - operator to subtract two vectors (each with x, y, and z components).
#include <iostream>
using namespace std;
class Vector {
double x, y, z;
public:
Vector(double x_val = 0, double y_val = 0, double z_val = 0) : x(x_val), y(y_val), z(z_val)
{}
// Overload the '-' operator
Vector operator-(const Vector& other) const {
4. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 4
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return Vector(x - other.x, y - other.y, z - other.z);
}
void display() const {
cout << "Vector(" << x << ", " << y << ", " << z << ")" << endl;
}
};
int main() {
Vector v1(5.0, 3.0, 2.0), v2(1.0, 1.5, 0.5);
Vector v3 = v1 - v2; // Uses overloaded '-' operator
v3.display(); // Output: Vector(4, 1.5, 1.5)
}
the - operator is overloaded to perform vector subtraction, allowing for intuitive vector
manipulation.
Overloading the == Operator for a Distance Class
The == operator can be overloaded to compare two Distance objects by checking if both their
feet and inches values are equal.
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
Distance(int f = 0, double i = 0.0) : feet(f), inches(i) {}
// Overload the '==' operator
bool operator==(const Distance& other) const {
return (feet == other.feet && inches == other.inches);
}
5. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 5
SHRI SHANKARACHARYA TECHNICAL CAMPUS
void display() const {
cout << feet << " feet " << inches << " inches" << endl;
}
};
int main() {
Distance d1(5, 9.5), d2(5, 9.5), d3(6, 4.0);
if (d1 == d2) {
cout << "d1 is equal to d2" << endl;
}
if (!(d1 == d3)) {
cout << "d1 is not equal to d3" << endl;
}
}
the == operator to compare if two Distance objects are equal, enhancing readability when
comparing complex data types.
Overloading the << (Insertion) Operator for Outputting Objects
The << operator is typically used for outputting data to the console. We can overload it to
print the contents of a Point class object directly.
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point(int x_val = 0, int y_val = 0) : x(x_val), y(y_val) {}
// Overload the '<<' operator
friend ostream& operator<<(ostream& out, const Point& p) {
out << "(" << p.x << ", " << p.y << ")";
6. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 6
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return out;
}
};
int main() {
Point p1(3, 4), p2(5, 7);
cout << "Point p1: " << p1 << endl; // Uses overloaded '<<' operator
cout << "Point p2: " << p2 << endl;
}
By overloading the << operator, we can print Point objects in a more readable format, making
it simpler to debug and display information.
Overloading the [] Operator for a Custom Array Class
The [] operator can be overloaded to provide array-like access to elements within a custom
array class.
cpp
Copy code
#include <iostream>
using namespace std;
class IntArray {
int arr[5];
public:
IntArray() {
for (int i = 0; i < 5; ++i)
arr[i] = 0;
}
// Overload the '[]' operator
int& operator[](int index) {
if (index >= 0 && index < 5)
7. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 7
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return arr[index];
else {
cout << "Index out of bounds" << endl;
exit(1);
}
}
void display() const {
for (int i = 0; i < 5; ++i)
cout << arr[i] << " ";
cout << endl;
}
};
int main() {
IntArray array;
array[0] = 10; // Uses overloaded '[]' operator
array[1] = 20;
array.display(); // Output: 10 20 0 0 0
}
the [] operator is overloaded to access and modify elements of a custom array class, giving it
array-like behavior and improving code readability.
Overloading the ++ Operator for Incrementing
The ++ operator can be overloaded to increment values, similar to its behavior with built-in
types.
#include <iostream>
using namespace std;
class Counter {
int value;
public:
Counter(int v = 0) : value(v) {}
8. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 8
SHRI SHANKARACHARYA TECHNICAL CAMPUS
// Overload the '++' operator (prefix)
Counter& operator++() {
++value;
return *this;
}
// Overload the '++' operator (postfix)
Counter operator++(int) {
Counter temp = *this;
++value;
return temp;
}
void display() const {
cout << "Counter value: " << value << endl;
}
};
int main() {
Counter c(5);
++c; // Uses overloaded prefix '++'
c.display(); // Output: Counter value: 6
c++; // Uses overloaded postfix '++'
c.display(); // Output: Counter value: 7
}
Type Conversion:
Type conversion in C++ refers to converting one data type into another. This can involve both
basic types (e.g., int, float) and user-defined types (e.g., classes). There are different types of
conversions in C++:
9. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 9
SHRI SHANKARACHARYA TECHNICAL CAMPUS
1. Implicit Conversion (Automatic Conversion): Performed automatically by the
compiler. For instance, when you assign an int to a float, the compiler automatically
converts it.
2. Explicit Conversion (Casting): When conversions need to be made explicitly, as in
static_cast, reinterpret_cast, const_cast, or dynamic_cast.
3. User-Defined Conversion: These are conversions defined by the programmer within
a class, allowing objects of that class to be converted to and from other types.
User-Defined Type Conversion
C++ supports user-defined type conversions to make class objects behave like built-in types
in certain situations. These conversions can be classified into:
1. Basic Type to Class Type Conversion: Converting a basic data type (like int, float,
etc.) to a user-defined class type.
2. Class Type to Basic Type Conversion: Converting an object of a class type to a basic
data type.
3. Class Type to Another Class Type Conversion: Converting an object of one class to
an object of another class.
1. Basic Type to Class Type Conversion
This is achieved by creating a constructor in the class that takes the basic type as a parameter.
The compiler will use this constructor to convert the basic type to the class type.
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
// Constructor that takes a single int parameter to convert from basic type to class type
Distance(int totalInches) {
feet = totalInches / 12;
inches = totalInches % 12;
}
void display() const {
cout << feet << " feet " << inches << " inches" << endl;
}
};
10. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 10
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
Distance d = 37; // 37 inches automatically converts to Distance object
d.display(); // Output: 3 feet 1 inches
}
Here, the constructor Distance(int totalInches) allows int to be automatically converted to a
Distance object. When 37 is assigned to d, this constructor is invoked to convert it into a
Distance instance.
2. Class Type to Basic Type Conversion
For this conversion, you define a conversion operator in the class. The operator keyword is
used to define the type to which the class object should be converted.
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
Distance(int f, double i) : feet(f), inches(i) {}
// Conversion operator to convert Distance to int
operator int() const {
return feet * 12 + inches; // Converts Distance object to total inches
}
};
int main() {
Distance d(3, 4.5);
int inches = d; // Converts Distance object to int
cout << "Distance in inches: " << inches << endl; // Output: Distance in inches: 40
}
operator int() allows the Distance object d to be converted to int. When assigned to inches,
the compiler uses this conversion operator to obtain the equivalent integer.
3. Class Type to Another Class Type Conversion
To convert an object from one class to another, you can either define a conversion constructor
in the destination class or define a conversion operator in the source class.
12. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 12
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Using Conversion Constructor in Destination Class
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
public:
Distance(int f, double i) : feet(f), inches(i) {}
int getFeet() const { return feet; }
double getInches() const { return inches; }
};
class MetricDistance {
double meters;
public:
// Conversion constructor that takes a Distance object
MetricDistance(const Distance& d) {
meters = (d.getFeet() * 12 + d.getInches()) * 0.0254; // Convert to meters
}
void display() const {
cout << meters << " meters" << endl;
}
};
int main() {
Distance d(3, 3.5);
MetricDistance md = d; // Converts Distance to MetricDistance using conversion
constructor
md.display(); // Output: 1.0049 meters
}
13. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 13
SHRI SHANKARACHARYA TECHNICAL CAMPUS
the MetricDistance class has a conversion constructor that takes a Distance object. This
constructor converts Distance to MetricDistance by calculating the equivalent metric value in
meters.
Important Points to Note
1. Automatic Conversion Risks: Be cautious with user-defined conversions, as they
may lead to ambiguous code or unexpected results when the compiler performs
automatic conversions.
2. Explicit Keyword: C++11 introduced the explicit keyword for constructors to
prevent unintended implicit conversions. When a constructor is marked explicit, it
cannot be used for implicit conversions.
Example with explicit Keyword
class Distance {
public:
explicit Distance(int totalInches) { /*...*/ }
};
Using explicit prevents the constructor from being used in implicit conversions, so Distance d
= 37; would result in an error unless explicitly cast: Distance d = Distance(37);
14. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 14
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Inheritance
Inheritance in C++ is a powerful object-oriented programming (OOP) feature that lets one
class inherit the properties and behaviors of another class. This enables code reuse,
modularity, and the formation of hierarchical class structures. Here’s a detailed explanation of
inheritance concepts, including defining derived classes, forms of inheritance, handling
ambiguity in multiple and multipath inheritance, virtual base classes, object slicing, function
overriding, and constructor/destructor execution order.
1. Introduction to Inheritance
Inheritance allows a derived class to acquire properties and behaviors (data members and
methods) of a base class. This establishes an "is-a" relationship between classes, meaning a
derived class can be considered a more specific version of a base class.
For example:
• A Car class can inherit from a Vehicle class, because a car "is-a" vehicle.
• Inheritance enables the derived class to extend or modify the base class functionality.
2. Defining Derived Classes
In C++, a derived class is created by using the following syntax:
cpp
Copy code
class DerivedClass : access_specifier BaseClass {
// Additional members and functions specific to DerivedClass
};
• access_specifier (usually public, protected, or private) controls the inheritance
visibility of base class members in the derived class.
• The derived class inherits all the accessible members of the base class.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
15. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 15
SHRI SHANKARACHARYA TECHNICAL CAMPUS
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal { // Dog is derived from Animal
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
return 0;
}
3. Forms of Inheritance
There are several forms of inheritance in C++:
• Single Inheritance: A derived class inherits from one base class.
• Multiple Inheritance: A derived class inherits from more than one base class.
• Multilevel Inheritance: A class derives from a class, which is also derived from
another class, creating a chain.
• Hierarchical Inheritance: Multiple classes inherit from a single base class.
• Hybrid Inheritance: A combination of multiple and multilevel inheritance (can lead
to ambiguity, resolved by virtual inheritance).
In C++, inheritance can take several forms, each representing a different kind of
relationship between base and derived classes. Here’s a breakdown of the different forms
of inheritance, along with examples for clarity:
1. Single Inheritance
16. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 16
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Single inheritance is when a derived class inherits from only one base class. This is the
simplest form of inheritance.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal { // Dog inherits from Animal
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
return 0;
}
In this example:
• Dog is the derived class and Animal is the base class.
• Dog inherits the eat() method from Animal and adds its own method, bark().
2. Multiple Inheritance
Multiple inheritance occurs when a derived class inherits from more than one base class.
This allows the derived class to combine the functionalities of multiple base classes but
17. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 17
SHRI SHANKARACHARYA TECHNICAL CAMPUS
can also introduce complexity due to potential conflicts (e.g., methods with the same
name in different base classes).
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Mammal {
public:
void walk() { cout << "Walking..." << endl; }
};
class Dog : public Animal, public Mammal { // Dog inherits from both Animal and
Mammal
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog d;
d.eat(); // From Animal
d.walk(); // From Mammal
d.bark(); // Defined in Dog
return 0;
}
18. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 18
SHRI SHANKARACHARYA TECHNICAL CAMPUS
In this example:
• Dog inherits both eat() from Animal and walk() from Mammal.
• This showcases how Dog can combine functionality from multiple base classes.
3. Multilevel Inheritance
Multilevel inheritance occurs when a derived class serves as a base class for another
class, creating a chain of inheritance. It establishes a hierarchy where each level builds
upon the previous level.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking..." << endl; }
};
class Puppy : public Dog { // Puppy inherits from Dog, which inherits from Animal
public:
void weep() { cout << "Weeping..." << endl; }
};
int main() {
Puppy p;
19. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 19
SHRI SHANKARACHARYA TECHNICAL CAMPUS
p.eat(); // Inherited from Animal
p.bark(); // Inherited from Dog
p.weep(); // Defined in Puppy
return 0;
}
In this example:
• Puppy inherits from Dog, which in turn inherits from Animal.
• Puppy has access to eat() (from Animal), bark() (from Dog), and weep() (defined in
Puppy), forming a chain of inheritance.
4. Hierarchical Inheritance
Hierarchical inheritance occurs when multiple derived classes inherit from a single base
class. This allows each derived class to share and possibly extend the properties and
behaviors of the base class.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal { // Dog inherits from Animal
public:
void bark() { cout << "Barking..." << endl; }
};
class Cat : public Animal { // Cat also inherits from Animal
20. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 20
SHRI SHANKARACHARYA TECHNICAL CAMPUS
public:
void meow() { cout << "Meowing..." << endl; }
};
int main() {
Dog d;
Cat c;
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
c.eat(); // Inherited from Animal
c.meow(); // Defined in Cat
return 0;
}
In this example:
• Both Dog and Cat are derived classes that inherit from the same base class, Animal.
• Dog and Cat share the eat() method but have their own unique methods: bark() for
Dog and meow() for Cat.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more of the above types of inheritance. It
often involves both multiple and multilevel inheritance and can lead to the diamond
problem.
Diamond Problem
The diamond problem occurs in hybrid inheritance when two derived classes inherit from
the same base class, and a further class inherits from both of them. This creates ambiguity
because the final derived class gets two copies of the base class members. Virtual
inheritance solves this problem by ensuring only one instance of the base class exists.
Example:
cpp
Copy code
#include <iostream>
using namespace std;
21. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 21
SHRI SHANKARACHARYA TECHNICAL CAMPUS
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Mammal : virtual public Animal { }; // Virtual inheritance
class Bird : virtual public Animal { }; // Virtual inheritance
class Bat : public Mammal, public Bird { };
int main() {
Bat b;
b.eat(); // No ambiguity due to virtual inheritance
return 0;
}
In this example:
• Animal is the base class, with Mammal and Bird as derived classes using virtual
inheritance.
• Bat inherits from both Mammal and Bird, but Animal appears only once in Bat's
hierarchy due to virtual inheritance, avoiding ambiguity.
4. Ambiguity in Multiple and Multipath Inheritance
In multiple and multipath inheritance, ambiguity may arise if two or more parent classes have
a member with the same name. This is common in complex hierarchies or "diamond-shaped"
inheritance structures, where a base class is inherited multiple times through different paths.
Example of Ambiguity:
cpp
Copy code
#include <iostream>
22. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 22
SHRI SHANKARACHARYA TECHNICAL CAMPUS
using namespace std;
class A {
public:
void show() { cout << "A::show" << endl; }
};
class B : public A { };
class C : public A { };
class D : public B, public C { };
int main() {
D d;
d.show(); // Error: ambiguous because of multiple inheritance from A
return 0;
}
Here, D inherits show() from both B and C, leading to ambiguity. To resolve this, you can
specify the path explicitly:
cpp
Copy code
d.B::show();
Virtual Base Class (Resolving the Diamond Problem):
To resolve ambiguity in complex inheritance structures, use virtual inheritance. By
declaring the base class as a virtual base class, C++ ensures only one instance of the base
class exists in the derived hierarchy.
cpp
Copy code
class A {
public:
void show() { cout << "A::show" << endl; }
23. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 23
SHRI SHANKARACHARYA TECHNICAL CAMPUS
};
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };
int main() {
D d;
d.show(); // No ambiguity due to virtual inheritance
return 0;
}
5. Object Slicing
Object slicing occurs when an object of a derived class is assigned to an object of the base
class, "slicing" off the derived part.
cpp
Copy code
#include <iostream>
using namespace std;
class Base {
public:
int x;
};
class Derived : public Base {
public:
int y;
};
24. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 24
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
Derived d;
d.x = 1;
d.y = 2;
Base b = d; // Object slicing occurs here
cout << b.x << endl; // Prints 1
// cout << b.y << endl; // Error: Base has no member y
return 0;
}
Here, the y member of Derived is "sliced off" when d is assigned to b. To avoid object
slicing, use pointers or references instead.
6. Overriding Member Functions
In function overriding, a derived class redefines a function of the base class. To enable
polymorphism, the base class function is declared as virtual, allowing the derived class
version to be called.
cpp
Copy code
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { cout << "Animal sound..." << endl; }
};
class Dog : public Animal {
public:
void sound() override { cout << "Dog barks..." << endl; }
25. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 25
SHRI SHANKARACHARYA TECHNICAL CAMPUS
};
int main() {
Animal* a = new Dog();
a->sound(); // Calls Dog's sound() due to virtual function
delete a;
return 0;
}
7. Order of Execution of Constructors and Destructors
When an object of a derived class is created, the base class constructor is called first,
followed by the derived class constructor. When destructing, the derived class destructor is
called first, followed by the base class destructor. This ensures that the base part of the
derived object is fully constructed and destructed.
cpp
Copy code
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base Constructor" << endl; }
~Base() { cout << "Base Destructor" << endl; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived Constructor" << endl; }
~Derived() { cout << "Derived Destructor" << endl; }
};
26. SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 26
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
Derived d;
return 0;
}
Output:
Copy code
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
In this example:
• The Base constructor is called before the Derived constructor.
• The Derived destructor is called before the Base destructor.