C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
This presentation discusses pointers, virtual functions, and polymorphism in C++. It defines pointers as variables that hold the addresses of other variables, and explains how pointers can point to objects through examples. Virtual functions allow a single base class pointer to refer to objects of derived classes by determining the function to call at runtime based on the object's type. Polymorphism means one name can have multiple forms, and it is a key feature of object-oriented programming that allows functions to work with objects of different types through virtual functions.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
C++ Object oriented concepts & programmingnirajmandaliya
油
This document discusses various C++ concepts related to functions and operators. It defines what a default pointer is and how it receives addresses passed to a called function. It also discusses reference variables, inline functions, friend functions, default arguments, passing objects as parameters, function overloading, static members, function pointers, and operator overloading. It provides examples and explanations for each concept.
Example for Virtual and Pure Virtual function.pdfrajaratna4
油
Virtual functions allow functions to be overridden in derived classes. They are useful for runtime polymorphism. A pure virtual function is a virtual function in a base class that has no definition, serving as a placeholder that must be overridden in derived classes. Derived classes that override all pure virtual functions from their base classes can have objects instantiated.
Virtual functions allow objects of derived classes to be referenced by pointers or references to the base class. This allows polymorphic behavior where calling code does not need to know the exact derived class, but the correct overridden function for that derived class will be called at runtime. Some key points:
- Virtual functions provide runtime polymorphism in C++. The correct function to call is determined by the actual object type, not the reference/pointer type.
- Pure virtual functions are declared in a base class but provide no definition - derived classes must override these to be instantiable.
- Constructors cannot be virtual but destructors can, and it is important to make base class destructors virtual to ensure proper cleanup
This document discusses pointers, virtual functions, and polymorphism in C++. It begins by defining pointers and how they can refer to and manipulate objects and memory addresses. It then explains virtual functions, which allow dynamic binding at runtime, and polymorphism. There are two types of polymorphism: compile-time polymorphism which includes function overloading, and runtime polymorphism using virtual functions. Virtual functions allow derived classes to override base class functions. The document also covers pure virtual functions, virtual constructors and destructors, and provides examples of how pointers and virtual functions enable polymorphism.
This document discusses various C++ concepts related to functions including:
- Default pointers which receive addresses passed to called functions.
- Reference variables which receive the reference of an actual variable passed to a function. Changing the reference variable directly changes the actual variable.
- Inline functions which eliminate context switching when defined inside a class or declared with the inline keyword.
- Friend functions which have access to private/protected members of a class they are declared as a friend to.
1. The document discusses various concepts related to functions in C++ such as function prototypes, passing arguments by reference, default arguments, inline functions, function overloading, and friend functions.
2. It provides examples to explain concepts like passing arguments by reference allows altering the original variable values, a friend function can access private members of a class, and function overloading allows using the same function name for different tasks based on the argument types.
3. The key benefits of concepts like inline functions, passing by reference, and function overloading are also summarized.
A pointer can point to an object by holding the object's address value. This is known as a "this pointer". A derived class inherits properties from its base class. A pointer to the base class can point to a derived class object, allowing access to both base and derived class members. Virtual functions ensure the correct overridden function is called at runtime based on the actual object type, rather than the pointer type. They are declared with the virtual keyword in the base class.
This code will generate a compile time error as Base is an abstract class due to pure virtual function show(). An abstract class cannot be instantiated.
The document provides definitions and explanations of key concepts in C++ like encapsulation, inheritance, polymorphism, overriding, multiple inheritance, constructors, destructors, virtual functions, storage qualifiers, functions, pointers, and name mangling. It discusses these concepts over multiple sections in detail with examples.
C++ (pronounced "see plus plus") is a computer programming language based on C. It was created for writing programs for many different purposes. In the 1990s, C++ became one of the most used programming languages in the world.
The C++ programming language was developed by Bjarne Stroustrup at Bell Labs in the 1980s, and was originally named "C with classes". The language was planned as an improvement on the C programming language, adding features based on object-oriented programming. Step by step, a lot of advanced features were added to the language, like operator overloading, exception handling and templates.
C++ is an object-oriented programming language created by Bjarne Stroustrup in 1985 that maintains aspects of C while adding object-oriented features like classes. C++ can be used to create small programs or large applications across many domains. Key concepts covered include functions, classes, inheritance, polymorphism, and memory management techniques like realloc() and free().
Pointer to Class & Object
This document discusses pointers to classes and objects in C++. It explains that class pointers allow for dynamic memory allocation of objects and polymorphism. It covers declaring class pointers, initializing them by pointing to existing objects or allocating memory dynamically, accessing members through pointers using the arrow operator, and pointers to class arrays. Pointers enable more flexible object handling in C++.
The document discusses various C++ concepts including static class members, the this pointer, friend functions and classes, dynamic memory management using new and delete operators, function overloading, operator overloading, templates, and inheritance. Static class members are accessible to all objects of the class and only one copy is created for the entire class. The this pointer refers to the current object from within non-static member functions. Friend functions and classes can access private members of other classes. Dynamic memory is allocated using new and freed using delete.
A class defines a data structure that can contain both data and functions as members. An object is an instance of a class that allocates memory for the class's data members. Classes allow the declaration of multiple objects that each have their own copies of the class's data members and can access the class's member functions. Constructors initialize an object's data members when it is created, while destructors perform cleanup tasks when an object is destroyed.
C++ is an object-oriented programming language created by Bjarne Stroustrup in 1985 that maintains aspects of C while adding object-oriented features like classes. C++ can be used to create everything from small programs to large applications and is a powerful general-purpose language. Inheritance allows code reusability by creating new classes from existing classes or base classes, where derived classes inherit capabilities from base classes but can add their own features and refinements. Polymorphism enables objects to react differently to the same function call through virtual functions, allowing different classes that inherit from a base class to provide their own implementation of a function.
Pointers,virtual functions and polymorphism cpprajshreemuthiah
油
This document discusses key concepts in object-oriented programming in C++ including polymorphism, pointers, pointers to objects and derived classes, virtual functions, and pure virtual functions. Polymorphism allows one name to have multiple forms through function and operator overloading as well as virtual functions. Pointers store the memory address of a variable rather than the data. Pointers can be used with objects, arrays, strings, and functions. Virtual functions allow calling a derived class version of a function through a base class pointer. Pure virtual functions define an abstract base class that cannot be instantiated.
The document discusses various C++ concepts including static class members and static member functions, the this pointer, friend functions, dynamic memory allocation using new and delete operators, function overloading and operator overloading, restrictions on operator overloading, type conversion, and templates and inheritance. It provides examples to illustrate concepts like static class members, friend functions, new and delete operators, function overloading, and operator overloading. The document serves as a reference for various advanced C++ programming concepts.
Structured Languages- Need and Characteristics of OOP, Data Types and Modifiers, Arrays, Classes, Objects, Pointers, References, Difference between Pointers and References, Inheritance, Constructors, Destructors, and Polymorphism.
This document provides an overview of object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, abstract classes, and pointers to objects. It defines each concept, provides syntax examples, and short programs to demonstrate how each concept works in practice. The document is submitted as part of a programming fundamentals course by Sidra Tahir to her instructor at COVT Post Graduate College for Women in Lahore, Pakistan.
This document discusses various C++ concepts related to functions including:
- Default pointers which receive addresses passed to called functions.
- Reference variables which receive the reference of an actual variable passed to a function. Changing the reference variable directly changes the actual variable.
- Inline functions which eliminate context switching when defined inside a class or declared with the inline keyword.
- Friend functions which have access to private/protected members of a class they are declared as a friend to.
1. The document discusses various concepts related to functions in C++ such as function prototypes, passing arguments by reference, default arguments, inline functions, function overloading, and friend functions.
2. It provides examples to explain concepts like passing arguments by reference allows altering the original variable values, a friend function can access private members of a class, and function overloading allows using the same function name for different tasks based on the argument types.
3. The key benefits of concepts like inline functions, passing by reference, and function overloading are also summarized.
A pointer can point to an object by holding the object's address value. This is known as a "this pointer". A derived class inherits properties from its base class. A pointer to the base class can point to a derived class object, allowing access to both base and derived class members. Virtual functions ensure the correct overridden function is called at runtime based on the actual object type, rather than the pointer type. They are declared with the virtual keyword in the base class.
This code will generate a compile time error as Base is an abstract class due to pure virtual function show(). An abstract class cannot be instantiated.
The document provides definitions and explanations of key concepts in C++ like encapsulation, inheritance, polymorphism, overriding, multiple inheritance, constructors, destructors, virtual functions, storage qualifiers, functions, pointers, and name mangling. It discusses these concepts over multiple sections in detail with examples.
C++ (pronounced "see plus plus") is a computer programming language based on C. It was created for writing programs for many different purposes. In the 1990s, C++ became one of the most used programming languages in the world.
The C++ programming language was developed by Bjarne Stroustrup at Bell Labs in the 1980s, and was originally named "C with classes". The language was planned as an improvement on the C programming language, adding features based on object-oriented programming. Step by step, a lot of advanced features were added to the language, like operator overloading, exception handling and templates.
C++ is an object-oriented programming language created by Bjarne Stroustrup in 1985 that maintains aspects of C while adding object-oriented features like classes. C++ can be used to create small programs or large applications across many domains. Key concepts covered include functions, classes, inheritance, polymorphism, and memory management techniques like realloc() and free().
Pointer to Class & Object
This document discusses pointers to classes and objects in C++. It explains that class pointers allow for dynamic memory allocation of objects and polymorphism. It covers declaring class pointers, initializing them by pointing to existing objects or allocating memory dynamically, accessing members through pointers using the arrow operator, and pointers to class arrays. Pointers enable more flexible object handling in C++.
The document discusses various C++ concepts including static class members, the this pointer, friend functions and classes, dynamic memory management using new and delete operators, function overloading, operator overloading, templates, and inheritance. Static class members are accessible to all objects of the class and only one copy is created for the entire class. The this pointer refers to the current object from within non-static member functions. Friend functions and classes can access private members of other classes. Dynamic memory is allocated using new and freed using delete.
A class defines a data structure that can contain both data and functions as members. An object is an instance of a class that allocates memory for the class's data members. Classes allow the declaration of multiple objects that each have their own copies of the class's data members and can access the class's member functions. Constructors initialize an object's data members when it is created, while destructors perform cleanup tasks when an object is destroyed.
C++ is an object-oriented programming language created by Bjarne Stroustrup in 1985 that maintains aspects of C while adding object-oriented features like classes. C++ can be used to create everything from small programs to large applications and is a powerful general-purpose language. Inheritance allows code reusability by creating new classes from existing classes or base classes, where derived classes inherit capabilities from base classes but can add their own features and refinements. Polymorphism enables objects to react differently to the same function call through virtual functions, allowing different classes that inherit from a base class to provide their own implementation of a function.
Pointers,virtual functions and polymorphism cpprajshreemuthiah
油
This document discusses key concepts in object-oriented programming in C++ including polymorphism, pointers, pointers to objects and derived classes, virtual functions, and pure virtual functions. Polymorphism allows one name to have multiple forms through function and operator overloading as well as virtual functions. Pointers store the memory address of a variable rather than the data. Pointers can be used with objects, arrays, strings, and functions. Virtual functions allow calling a derived class version of a function through a base class pointer. Pure virtual functions define an abstract base class that cannot be instantiated.
The document discusses various C++ concepts including static class members and static member functions, the this pointer, friend functions, dynamic memory allocation using new and delete operators, function overloading and operator overloading, restrictions on operator overloading, type conversion, and templates and inheritance. It provides examples to illustrate concepts like static class members, friend functions, new and delete operators, function overloading, and operator overloading. The document serves as a reference for various advanced C++ programming concepts.
Structured Languages- Need and Characteristics of OOP, Data Types and Modifiers, Arrays, Classes, Objects, Pointers, References, Difference between Pointers and References, Inheritance, Constructors, Destructors, and Polymorphism.
This document provides an overview of object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, abstract classes, and pointers to objects. It defines each concept, provides syntax examples, and short programs to demonstrate how each concept works in practice. The document is submitted as part of a programming fundamentals course by Sidra Tahir to her instructor at COVT Post Graduate College for Women in Lahore, Pakistan.
Preface: The ReGenX Generator innovation operates with a US Patented Frequency Dependent Load Current Delay which delays the creation and storage of created Electromagnetic Field Energy around the exterior of the generator coil. The result is the created and Time Delayed Electromagnetic Field Energy performs any magnitude of Positive Electro-Mechanical Work at infinite efficiency on the generator's Rotating Magnetic Field, increasing its Kinetic Energy and increasing the Kinetic Energy of an EV or ICE Vehicle to any magnitude without requiring any Externally Supplied Input Energy. In Electricity Generation applications the ReGenX Generator innovation now allows all electricity to be generated at infinite efficiency requiring zero Input Energy, zero Input Energy Cost, while producing zero Greenhouse Gas Emissions, zero Air Pollution and zero Nuclear Waste during the Electricity Generation Phase. In Electric Motor operation the ReGen-X Quantum Motor now allows any magnitude of Work to be performed with zero Electric Input Energy.
Demonstration Protocol: The demonstration protocol involves three prototypes;
1. Protytpe #1, demonstrates the ReGenX Generator's Load Current Time Delay when compared to the instantaneous Load Current Sine Wave for a Conventional Generator Coil.
2. In the Conventional Faraday Generator operation the created Electromagnetic Field Energy performs Negative Work at infinite efficiency and it reduces the Kinetic Energy of the system.
3. The Magnitude of the Negative Work / System Kinetic Energy Reduction (in Joules) is equal to the Magnitude of the created Electromagnetic Field Energy (also in Joules).
4. When the Conventional Faraday Generator is placed On-Load, Negative Work is performed and the speed of the system decreases according to Lenz's Law of Induction.
5. In order to maintain the System Speed and the Electric Power magnitude to the Loads, additional Input Power must be supplied to the Prime Mover and additional Mechanical Input Power must be supplied to the Generator's Drive Shaft.
6. For example, if 100 Watts of Electric Power is delivered to the Load by the Faraday Generator, an additional >100 Watts of Mechanical Input Power must be supplied to the Generator's Drive Shaft by the Prime Mover.
7. If 1 MW of Electric Power is delivered to the Load by the Faraday Generator, an additional >1 MW Watts of Mechanical Input Power must be supplied to the Generator's Drive Shaft by the Prime Mover.
8. Generally speaking the ratio is 2 Watts of Mechanical Input Power to every 1 Watt of Electric Output Power generated.
9. The increase in Drive Shaft Mechanical Input Power is provided by the Prime Mover and the Input Energy Source which powers the Prime Mover.
10. In the Heins ReGenX Generator operation the created and Time Delayed Electromagnetic Field Energy performs Positive Work at infinite efficiency and it increases the Kinetic Energy of the system.
This PPT covers the index and engineering properties of soil. It includes details on index properties, along with their methods of determination. Various important terms related to soil behavior are explained in detail. The presentation also outlines the experimental procedures for determining soil properties such as water content, specific gravity, plastic limit, and liquid limit, along with the necessary calculations and graph plotting. Additionally, it provides insights to understand the importance of these properties in geotechnical engineering applications.
Indian Soil Classification System in Geotechnical EngineeringRajani Vyawahare
油
This PowerPoint presentation provides a comprehensive overview of the Indian Soil Classification System, widely used in geotechnical engineering for identifying and categorizing soils based on their properties. It covers essential aspects such as particle size distribution, sieve analysis, and Atterberg consistency limits, which play a crucial role in determining soil behavior for construction and foundation design. The presentation explains the classification of soil based on particle size, including gravel, sand, silt, and clay, and details the sieve analysis experiment used to determine grain size distribution. Additionally, it explores the Atterberg consistency limits, such as the liquid limit, plastic limit, and shrinkage limit, along with a plasticity chart to assess soil plasticity and its impact on engineering applications. Furthermore, it discusses the Indian Standard Soil Classification (IS 1498:1970) and its significance in construction, along with a comparison to the Unified Soil Classification System (USCS). With detailed explanations, graphs, charts, and practical applications, this presentation serves as a valuable resource for students, civil engineers, and researchers in the field of geotechnical engineering.
Integration of Additive Manufacturing (AM) with IoT : A Smart Manufacturing A...ASHISHDESAI85
油
Combining 3D printing with Internet of Things (IoT) enables the creation of smart, connected, and customizable objects that can monitor, control, and optimize their performance, potentially revolutionizing various industries. oT-enabled 3D printers can use sensors to monitor the quality of prints during the printing process. If any defects or deviations from the desired specifications are detected, the printer can adjust its parameters in real time to ensure that the final product meets the required standards.
Lecture -3 Cold water supply system.pptxrabiaatif2
油
The presentation on Cold Water Supply explored the fundamental principles of water distribution in buildings. It covered sources of cold water, including municipal supply, wells, and rainwater harvesting. Key components such as storage tanks, pipes, valves, and pumps were discussed for efficient water delivery. Various distribution systems, including direct and indirect supply methods, were analyzed for residential and commercial applications. The presentation emphasized water quality, pressure regulation, and contamination prevention. Common issues like pipe corrosion, leaks, and pressure drops were addressed along with maintenance strategies. Diagrams and case studies illustrated system layouts and best practices for optimal performance.
Air pollution is contamination of the indoor or outdoor environment by any ch...dhanashree78
油
Air pollution is contamination of the indoor or outdoor environment by any chemical, physical or biological agent that modifies the natural characteristics of the atmosphere.
Household combustion devices, motor vehicles, industrial facilities and forest fires are common sources of air pollution. Pollutants of major public health concern include particulate matter, carbon monoxide, ozone, nitrogen dioxide and sulfur dioxide. Outdoor and indoor air pollution cause respiratory and other diseases and are important sources of morbidity and mortality.
WHO data show that almost all of the global population (99%) breathe air that exceeds WHO guideline limits and contains high levels of pollutants, with low- and middle-income countries suffering from the highest exposures.
Air quality is closely linked to the earths climate and ecosystems globally. Many of the drivers of air pollution (i.e. combustion of fossil fuels) are also sources of greenhouse gas emissions. Policies to reduce air pollution, therefore, offer a win-win strategy for both climate and health, lowering the burden of disease attributable to air pollution, as well as contributing to the near- and long-term mitigation of climate change.
2. POINTERS
Pointer is a derived data type that refers to the address of another variable.
A pointer variable tells that where to get the data instead of telling the
actual data.
The declaration of the pointer is based on the data type of the variable it
points to.
data-type *pointer-variable
At any point of time a pointer variable can point to only one data type.
int *ptr;
Here ptr contains the memory location of any integer variable.
e.g. int *ptr , a; //Declaration
ptr=&a; //Initialization
3. int a = 25;
int *p;
p = &a;
cout<<"&a:"<<&a;
cout<<"p:"<<p;
cout<<"&p:"<<&p;
cout<<"*p:"<<*p;
cout<<"*(&a):"<<*(&a);
(*p)++;
cout<<"*p:"<<*p;
cout<<"a:"<<a;a
25 1000
p
a
1000 2000
4. int a = 25;
int *p,**s;
p = &a;
s = &p;
cout<<"n*p:"<<*p;
cout<<"n*s:"<<*s;
cout<<"n**s:"<<**s;
cout<<"n*(*(&p)):"<<*(*(&p));
cout<<"n***(&s):"<<***(&s);
5. POINTERS WITH ARRAYS
Pointers are associated with arrays as:
Pointers are useful to allocate arrays dynamically
Efficient tools to access the elements of an array.
We can declare pointers to arrays as ;
int *ptr;
ptr = number[0]; OR ptr = number;
An array of Pointer is an array of addresses i.e all the elements of the Pointer
array points to an item of the data array. An array of Pointer is declared as
int *abc[10];
It is an array of ten pointers ie. Addresses all of them points to an integer.
Before initializing they point to some unknown values in the memory space.
6. int main ()
{
int arr[5] = {10,20,30,40,50};
int *ptr;
ptr = &arr[0];
for ( int i = 0; i < 5; i++ )
{
cout <<"*(ptr+" << i <<"):";
cout <<*(ptr + i) << endl;
}
return 0;
}
7. POINTERS TO OBJECTS
Just like pointers to normal variables and functions, we can
have pointers to class members (variables and methods).
class ABC
{
public:
int a=50;
};
int main()
{
ABC ob1;
ABC *ptr;
ptr = &ob1;
cout << ob1.a;
cout << ptr->a; //
Accessing members of
class with pointer
}
8. class demo{
int i;
public:
demo(int x){
i=x; }
int getdata(){
return i;}
};
int main()
{
demo d[3]={55,66,77};
demo *ptr=d; //similar to *ptr=&d[0]
for(int i=0;i<3;i++)
{
cout<<ptr->getdata()<<endl;
ptr++;
}
}
9. Practice Program
Create a class student having private members marks,
name and public members rollno, getdata(),
printdata(). Demonstrate concept of pointer to class
members for array of 3 objects.
10. THIS POINTER
this pointer represent an object that invoke or call a member
function.
It will point to the object for which member function is called.
It is automatically passed to a member function when it is
called.
It is also called as implicit argument to all member function.
Friend functions can not be accessed using this pointer,
because friends are not members of a class.
Only member functions have a this pointer.
A static member function does not have this pointer.
11. THIS POINTER
Following are the situations where this pointer is used.
When local variables name is same as members name
To return reference to the calling object
12. class sample
{
int a,b;
public:
void input(int a,int b){
this->a = a + b;
this->b = a - b;
}
void output(){
cout<<"a = "<<a;
cout<<"b = "<<b;
}
};
int main()
{
sample ob1;
int a=5,b=8;
ob1.input(a,b);
ob1.output();
}
13. class Test
{
int x; int y;
public:
Test& setX(int a) { x = a; return *this; } //Reference to the calling object can be returned
Test& setY(int b) { y = b; return *this; }
void print() {
cout << "x = " << x ;
cout << " y = " << y;
}
};
int main()
{
Test obj1;
obj1.setX(10).setY(20); // chain function calls
obj1.print();
}
14. POINTERS TO DERIVED CLASS
We can use pointers not only to the base objects but also to the objects of
derived classes.
Pointers to the base classes are type-compatible to the objects of the derived
classes. Hence, A single pointer variable of base type can be made to point to
objects belonging to base as well as derived classes.
E.g. Here B is a base class, D is Derived class.
B *cptr;
B b;
D d;
cptr=&b;
we can also make the cptr to point to object d also.
cptr=&d;
As d is an object derived from the class B
15. POINTERS TO DERIVED CLASS
We can access those members of derived class which are
inherited from base class by base class pointer.
But we cannot access original member of derived class which
are not inherited from base class using base class pointer.
We can access original member of derived class using pointer of
derived class.
16. VIRTUAL FUNCTIONS
A virtual function is a member function that is declared within a base class
and redefined by a derived class.
To create a virtual function, precede the function's declaration in the base
class with the keyword virtual.
When virtual function accessed "normally," it behave just like any other type
of class member function. But when it is accessed via a pointer it supports
run time polymorphism.
Base class and derived class have same function name and base class
pointer is assigned address of derived class object then also pointer will
execute base class function.
After making virtual function, the compiler will determine which function to
execute at run time on the basis of assigned address to pointer of base class.
17. RULES FOR VIRTUAL FUNCTIONS
The virtual functions must be member of any class.
They cannot be static members.
They are accessed by using object pointers.
A virtual function can be a friend of another class.
A virtual function in a base class must be defined, even though it may not be used.
We cannot have virtual constructors, but we can have virtual destructors.
The derived class pointer cannot point to the object of base class.
When a base pointer points to a derived class, then also it is incremented or
decremented only relative to its base type. Therefore we should not use this method
to move the pointer to the next object.
If a virtual function is defined in base class, it need not be necessarily redefined in
the derived class. In such cases, call will invoke the base class.
18. PURE VIRTUAL FUNCTIONS
A pure virtual function is virtual function that has no definition within the base
class.
A pure virtual function means do nothing function.
We can say empty function. A pure virtual function has no definition relative
to the base class.
Programmers have to redefine pure virtual function in derived class, because
it has no definition in base class.
A class containing pure virtual function cannot be used to create any direct
objects of its own.
This type of class is also called as abstract class.
20. ABSTRACT CLASS
A class that contains at least one pure virtual function is
called abstract class.
You can not create objects of an abstract class, you can
create pointers and references to an abstract class.
21. VIRUTAL DESTRUCTOR
Deleting a derived class object using a pointer of base class
type that has a non-virtual destructor results in undefined
behavior. To correct this situation, the base class should be
defined with a virtual destructor.
Making base class destructor virtual guarantees that the
object of derived class is destructed properly, i.e., both base
class and derived class destructors are called.
23. INTRODUCTION
C++ templates are a powerful mechanism for code reuse,
as they enable the programmer to write code that
behaves the same for any data type.
By template we can define generic classes and functions.
In simple terms, you can create a single function or a class
to work with different data types using templates.
It can be considered as a kind of macro. When an object
of a specific type is defined for actual use, the template
definition for that class is substituted with the required data
type.
25. FUNCTION TEMPLATE
A function template specifies how an individual function can
be constructed.
We write a generic function that can be used for different data
types.
Syntax:
template <class T>
T functionname(T arg1,T arg2)
{
function body;
}
26. A generic function defines a general set of operations that will be applied to
various types of data.
A generic function has the type of data that it will operate upon passed to
it as a parameter.
Using this mechanism, the same general procedure can be applied to a
wide range of data.
For example the Quicksort algorithm is the same whether it is applied to an
array of integers or an array of floats. It is just that the type of data being
sorted is different.
By creating a generic function, you can define, independent of any data,
the nature of the algorithm.
Once this is done, the compiler automatically generates the correct code
for the type of data that is actually used when you execute the function.
In essence, when you create a generic function you are creating a function
that can automatically overload itself.
A generic function is also called a template function. When the compiler
creates a specific version of the function, it is said to have created a
generated function.
Generic functions may be overloaded.
27. Suppose you write a function printData:
void printData(int value){
cout<<"The value is "<<value;
}
Now if you want to print double values or string values, then you have to
overload the function:
void printData(float value){
cout<<"The value is "<<value;
}
void printData(char *value) {
cout<<"The value is "<<*value;
}
To perform same operation with different data type, we have to write same
code multiple time.
28. C++ provides templates to reduce this type of duplication of code.
template<class T>
void printData(T value){
cout<<"The value is "<<value;
}
We can now use printData for any data type. Here T is a template parameter
that identifies a type.
Then, anywhere in the function where T appears, it is replaced with whatever
type the function is instantiated.
int i=3;
float d=4.75;
char *s="hello";
printData(i); // T is int
printData(d); // T is float
printData(s); // T is string
29. OVERLOADED FUNCTION TEMPLATE
Like ordinary functions, function templates can be overloaded.
We can have different function definitions with the same function name so that when
that name is used in a function call, a C++ compiler must decide which one of the
various functions to call.
The rules for this decision may become rather complicated, even without templates.
Generic functions perform the same operation for all the versions of a function except
the data type differs.
The overloading resolution is accomplished as follows:
Call an ordinary function that has an exact match.
Call a template function could be created with an exact match.
Try normal overloading resolution to ordinary functions and call the one that matches.
An error is generated if no match is found. Note that no automatic conversions are
applied to arguments on the template functions.
30. CLASS TEMPLATE
Sometimes, you need a class implementation that is same for all classes, only the data
types used are different.
Normally, you would need to create a different class for each data type OR create
different member variables and functions within a single class.
Syntax:
template <class type>
class classname
{
type member1;
public:
type fun();
};
31. CLASS TEMPLATE
The object of template class is created as follows
class name <data type> object name;
33. Generic classes are useful when a class contains generalizable
logic.
For example, the same algorithm that maintains a queue of
integers will also work for a queue of characters. Also, the same
mechanism that maintains a linked list of mailing addresses will
also maintain a linked of auto part information.
By using a generic class, you can create a class that will
maintain a queue, a linked list, and so on for any type of data.
The compiler will automatically generate the correct type of
object based upon the type you specify when the object is
created.
C++ provides a library that is built upon template classes. This
library is usually referred to as the Standard Template Library, or
STL for short.
It provides generic versions of the most commonly used
algorithms and data structures.
34. CLASS TEMPLATE INHERITANCE
The template class can also act as base class.
There are 3 cases:-
Derive a template class and add new member to it, the base class must be
of template type.
Derive a class from non-template class add new template type members
to derive class.
Derive a class from a template base class and omit the template features
in the derive class.
This can be done by declaring the type while deriving the class.
All the template based variables are substituted with basic data type.
35. SUMMARY
C++ supports a mechanism known as template to implement the concept of generic
programming.
Template allows us to generate a family of classes or a family of functions to handle different
data types.
Template classes and functions eliminate code duplication for different types and thus make
the program development easier and more manageable.
We can use multiple parameters in both the class templates and function templates.
A specific class created from a class template is called a template class and the process of
creating a template class is known as instantiation.
Like other functions, template functions can be overloaded.
Member function of a class template must be defined as function templates using the
parameters of the class template.
We may also use non type parameters such basic or derived data types as arguments
templates.
36. CONTAINERSHIP
We can create an object of one class into another and that
object will be a member of the class. This type of relationship
between classes is known as containership or has_a relationship
as one class contain the object of another class.
And the class which contains the object and members of
another class in this kind of relationship is called a container class.
The object that is part of another object is called contained
object, whereas object that contains another object as its part or
attribute is called container object.
#7: When accessing members of a class given a pointer to an object, use the arrow (>) operator instead of the dot operator.
#8: When a pointer incremented it points to next element of its type.
An integer pointer will point to the next integer.
The same is true for pointer to objects.
#13: When a reference to a local object is returned, the returned reference can be used to油chain function calls油on a single object.
#21: As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor (even if it does nothing)