C - C++ Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Notes by Lov Lamba

C Programming Language

• Who was the founder of C language & When was it devloped?


Dennis Ritchie . C language was developed in 1972 at bell laboratories of AT&T.

• Who is the main contributor in designing the C language after Dennis Ritchie?
Brain Kernighan.

• What are the features of the C language?


- Procedural language: C is a procedural language & simple because it follows the structured
approach, i.e., a program is broken into parts

- Portable: C is called a mid-level programming language because it binds the low level and high
-level programming language.

- Mid Level: C is a mid-level programming language as it combines the low- level language with
the features of the high-level language.

- Fast Speed: C language is very fast as it uses a powerful set of data types and operators.

- Memory Management: C provides an inbuilt memory function that saves the memory and
improves the efficiency of our program.

- Extensible: C is an extensible language as it can adopt new features in the future.

- Pointer: C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
• How does a program execute in C ? - Program execution in C by GFG

• C/C++ preprocessors - Preprocessors by GFG

• Rules for defining variable & Types of variable

Variable in C by JAVATPOINT

• Scope of variable
Scope of the variable can be defined as the part of the code area where the variables declared
in the program can be accessed directly. In C, all identifiers are lexically (or statically) scoped.
Scoping is generally divided into two classes, lets understand with an example :-

int x = 10;

int f() {

return x; }

int g() {

int x = 20;

return f(); }

main() {

printf(g()); }

1. Static Scoping :- In static scoping the compiler first searches in the current block, then in
global variables, then in successively smaller scopes. C, C++ and Java, variables are always
statically (or lexically) scoped.

Output for the above program :- 10

2. Dynamic Scoping :- in dynamic scoping the compiler first searches the current block and then
successively all the calling functions. Dynamic scoping is very uncommon in the familiar
languages but Perl supports both dynamic and static scoping.
Output for the above program :- 20

Static scoping also makes it much easier to make a modular code as programmer can figure out
the scope just by looking at the code. In contrast, dynamic scope requires the programmer to
anticipate all possible dynamic contexts.

• Difference between Parameters & Arguments

• Differentiate between call by value and call by reference


• What is command line argument?
The argument passed to the main() function while executing the program is known as
command line argument. For example:

main(int count, char *args[]){

• What is a C Token?
Keywords, Constants, Special Symbols, Strings, Operators, Identifiers used in C program are
referred to as C Tokens.

• Keywords & Identifiers


Keywords are predefined, reserved words used in programming that have special meanings to
the compiler. Keywords are part of the syntax and they cannot be used as an identifier.

Identifier refers to name given to entities such as variables, functions, structures etc. Identifiers
must be unique.

• Signed & Unsigned keyword in C


signed keyword is used for those variables which can take positive as well as negative values.
unsigned keyword is used for those variables which can take only values which are zero or
positive i.e., without - (negative sign).

• What is Qualifiers in C? - Qualifiers in C by JOURNALDEV

• C macros - C-Macros by JAVATPOINT

• Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

Note :- Structure, Union & Enum are also called as user-defined data types.

• Type cast & it's type


A type cast is basically a conversion from one type to another. There are two types of type
conversion:

- Implicit Type Conversion

Also known as ‘automatic type conversion’.Done by the compiler on its own, without any
external trigger from the user.Generally takes place when in an expression more than one data
type is present. In such condition type conversion (type promotion) takes place to avoid loss of
data.

Example of Type Implicit Conversion:

int x = 10;

char y = 'a';

x = x + y;

float z = x + 1.0;

printf("x = %d, z = %f", x, z);

Output: x = 107, z = 108.000000

- Explicit Type Conversion

This process is also called type casting and it is user defined. Here the user can type cast the
result to make it of a particular data type.

Example of Type Explicit Conversion:

double x = 1.2;

int sum = (int)x + 1;

printf("sum = %d", sum);

Output: sum = 2

• Explain data type Enum


Enumeration (or enum) is a user defined data type . It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.

// An example program to demonstrate working of enum in C

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

enum week day;

day = Wed;

printf("%d",day);

return 0;

Note :- & (ampersand) means the address-of, mainly used to pass by reference. *(asterisk)
means the dereference of a pointer variable, meaning to get the value of that pointer variable.
Without an asterisk, an initialized pointer holds a memory address not its value.

• Structure in C
A structure is a user defined data type in C/C++. A structure creates a data type that can be
used to group items of possibly different types into a single type.

‘struct’ keyword is used to create a structure. Following is an example :-

Note :- In C++, the struct keyword is optional before in declaration of a variable. In C, it is


mandatory.

Structure members cannot be initialized with declaration. The reason for above error is simple,
when a datatype is declared, no memory is allocated for it. Memory is allocated only when
variables are created. Structure members can be initialized using curly braces ‘{}’. For example,
following is a valid initialization.

For Examples & more on struct - Structure in C by GFG

• Union in C
refer to this - Union in C by GFG

• What is pointer to pointer in C?


In case of a pointer to pointer concept, one pointer refers to the address of another pointer.
The pointer to pointer is a chain of pointers. Generally, the pointer contains the address of a
variable. The pointer to pointer contains the address of a first pointer.
• Dangling Pointer variable
A Pointer in C Programming is used to point the memory location of an existing variable. In case
if that particular variable is deleted and the Pointer is still pointing to the same memory
location, then that particular pointer variable is called as a Dangling Pointer Variable.

• Dyanamic Memory allocation in C


Suppose I have declared an array of size 9 . But,

- If there is a situation where only 5 elements are needed to be entered in this array. In this
case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 9 to 5.

- Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But
there is a need to enter 3 more elements in this array. In this case 3 indices more are required.
So the length (size) of the array needs to be changed from 9 to 12.

So, Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.

There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate
dynamic memory allocation in C programming. They are :-

1. malloc() & calloc() :- “memory allocation" & “contiguous allocation” both method are used
to dynamically allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form.
If space is insufficient, allocation fails and returns a NULL pointer.

Note :- The only difference between them is that malloc() initializes each block with default
garbage value while Calloc() initializes each block with a default value ‘0’.

2. free() :- “free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it. Syntax: free(ptr);

3. realloc() :- “realloc” or “re-allocation” method in C is used to dynamically change the


memory allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-
allocate memory. re-allocation of memory maintains the already present value and new blocks
will be initialized with default garbage value.

If space is insufficient, allocation fails and returns a NULL pointer.


• What do you mean by Memory Leak?
Memory Leak can be defined as a situation where programmer allocates dynamic memory to
the program but fails to free or delete the used memory after the completion of the code. This
is harmful if daemons and servers are included in the program.

• How does a positive & negative integer stored in memory ?


To store positive integer, Example :- 65, Binary equivalent of 65 is (1000001) 2 . The MSB (most
significant bit) bit is used to indicate whether the number is positive or negative. For positive
numbers MSB will be 0 & for negative numbers MSB will be 1. In our case, 65 is positive so MSB
will be 0.

This binary equivalent of 65 will be stored in 32-bit memory like below,

To store a negative integer, Calculate the two’s complement of the same positive integer.
follow the following steps :- Let's Say we want to store -10.

Step-1 − First we will calculate binary of 10 . i.e., 10101

Step-2 − Calculate the One’s complement( the zeroes would be changed to one and one to
zeroes) of 5: 0101

Step-3 − Add 1 to above to ge the two's complement , giving 0110, which is -10
To store char, For example, if we want to store char ‘A’ in computer, the corresponding ASCII
value will be stored in computer.ASCII value for capital A is 65.To store character value,
computer will allocate 1 byte (8 bit) memory.65 will converted into binary form which is
(1000001) 2. Because computer knows only binary number system.Then 1000001 will be stored
in 8-bit memory.

Note :- We can also store char value in int variable( will be stored in binary of the ascii code of
the char ) & int value in char variable. Consider the below link for the example. How integers
are stored in char variable ?

• Different Storage classes in C? Explain Register class.


refer this article - Storage classes in C by GFG

• Two Phases in a recursive function


The recursive function works in two phases:

1. Winding phase: In Winding phase, the recursive function keeps calling itself. This phase ends
when the base condition is reached.

2. Unwinding phase: When the base condition is reached, unwinding phase starts and control
returns back to the original call.

Let's take an example:

#include<stdio.h>

void rec();
int main(){

rec(1);

return 0; }

void rec(int n) {

printf("Winding phase: Level = %d\n", n);

if(n<3) {

rec(n+1); }

printf("Unwinding phase: Level = %d\n", n); }

• Difference between declaring a header file with < > and ” “?


Ans: If the Header File is declared using < > then the compiler searches for the header file
within the Built-in Path. If the Header File is declared using ” ” then the compiler will search for
the Header File in the current working directory and if not found then it searches for the file in
other locations.

• Which statement is efficient and why? x=x+1; or x++; ? Difference between


x++ & ++x.
x++; is the most efficient statement as it just a single instruction to the compiler while the other
is not. ++x happens prior to assignment (pre-increment), but x++happens after assignment
(post-increment). x++ executes the statement and then increments the value. ++x increments
the value and then executes the statement.

• Purpose of printf() and scanf() & the format specifier


printf() is used to print the values on the screen. To print certain values, and on the other hand,
scanf() is used to scan the values. We need an appropriate datatype format specifier for both
printing and scanning purposes. For example,

%d: It is a datatype format specifier used to print and scan an integer value.

%s: It is a datatype format specifier used to print and scan a string.

%c: It is a datatype format specifier used to display and scan a character value.

%f: It is a datatype format specifier used to display and scan a float value.

• What are the limitations of scanf() and how can it be avoided?


It is not possible to enter a multiword string into a single variable using scanf(). To avoid this the
gets( ) function is used. It gets a string from the keyboard and is terminated when enter key is
pressed. Here the spaces and tabs are acceptable as part of the input string.

• How can you print a string with the symbol % in it?


There is no escape sequence provided for the symbol % in C. So, to print % we should use ‘%%’
as shown below.

printf(“there are 90%% chances of rain tonight”);

• What is the purpose of sprintf() function?


The sprintf() stands for "string print." The sprintf() function does not print the output on the
console screen. It transfers the data to the buffer. It returns the total number of characters
present in the string. Let's see a simple example:-

#include<stdio.h>
int main()

char a[20];

int n=sprintf(a,"javaToint");

printf("value of n is %d",n);

return 0;}

Output:

value of n is 9

• What is the newline escape sequence?


The new line escape sequence is represented by "\n". It inserts a new line on the output screen.

• What is /0 character ?
The Symbol mentioned is called a Null Character. It is considered as the terminating character
used in strings to notify the end of the string to the compiler.

• Explain toupper() in C/C++


toupper() is a function designed to convert lowercase words/characters into upper case.

• rand() & srand() in C/C++


The rand() function is used in C/C++ to generate random numbers in the range [0, RAND_MAX).
If random numbers are generated with rand() without first calling srand(), your program will
create the same sequence of numbers each time it runs.for ex - rand() & srand() in C/C++

• Difference between getc(), getchar(), getch() and getche()


refer this article - by GFG

Note :- getch() or getche() does not hold the screen, rather it wait for user to hit any character
from keyboard. The next statement after getch(); will only execute when there will be any
generation of character by user from keyboard. getch() is library function define in conio. It is
used to get a single character from the console.

• Basic File Handling Operations in C


refer this article - File Handling in C by GFG

• Can I create a customized Head File in C language?


It is possible to create a new header file. Create a file with function prototypes that need

to be used in the program. Include the file in the ‘#include’ section in its name.

• Can we compile a program without main() function?


Yes, we can compile, but it can't be executed. But, if we use #define, we can compile and run a
C program without using the main() function. For example:

#include<stdio.h>

#define start main

void start() {

printf("Hello");

• Write a C program to print hello world without using a semicolon (;).


#include <stdio.h>

void main()
{

if(printf("hello world")){}

Output:

hello world

• Write a program to swap two numbers without using the third variable.

C++ Programming Language


• Differences between C and C++
Difference between C and C++ by GFG

• Difference between stldio.h, conio.h & iostream


"stdio.H" is short name of Standard Input & Output Header . It includes basic functions like
printf() (to print on screen), scanf() (used to take input from user) etc.

"conio.h" stands for Console Input & Output header & isn't used anymore. It was used in old
Turbo C compiler which are 16-bit . It includes functions like clrscr() (Clears the Screen), getch()
(it holds the screen until and input from keyboard is received).

"iostream" - standard C++ input and output, contains objects like cout, cin and cerr. works with
C++ streams, which are objects that manages IO.It is the default IO choice for C++ projects.

• What does 'using namespace std' mean in C++?


"using namespace std" in C++ by TUTORIALSPOINT

• Is it possible for a C++ program to be compiled without the main() function?


Yes, it is possible. However, as the main() function is essential for the execution of the program,
the program will stop after compiling and will not execute.

• Can we have a String primitive data type in C++?


No, we cannot have a String Primitive data type in C++. Instead, we can have a class from the
Standard Template Library (STL).

• Define a class template?


A class template is a name given to the generic class. This allows a function or class to work on
many different data types without being rewritten for each one. The use of the keyword
template is made for defining a class template. For ex Templates by GFG.

• Explain STL & its class vector in C++ .


The Standard Template Library (STL) is a set of C++ template classes to provide common programming
data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes,
algorithms, and iterators. It is a generalized library and so, its components are parameterized. A working
knowledge of template classes is a prerequisite for working with STL.

STL has four components

- Algorithms

- Containers

- Functions

- Iterators

Vector in C++ STL

Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is
inserted or deleted, with their storage being handled automatically by the container. Vector elements
are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors,
data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a
need of extending the array. Removing the last element takes only constant time because no resizing
happens. Inserting and erasing at the beginning or in the middle is linear in time.

• What is a reference in C++?


A reference is like a pointer. It is another name of an already existing variable. Once a reference
name is initialized with a variable, that variable can be accessed by the variable name or
reference name both.

For example-

int x=10;

int &ref=x; //reference variable


If we change the value of ref it will be reflected in x. Once a reference variable is initialized it
cannot refer to any other variable. We can declare an array of pointers but an array of
references is not possible.

• What are the differences between references and pointers?


References are less powerful than pointers

1) Once a reference is created, it cannot be later made to reference another object; it cannot
be reseated. This is often done with pointers.

2) References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing.

3) A reference must be initialized when declared. There is no such restriction with pointers

Due to the above limitations, references in C++ cannot be used for implementing data
structures like Linked List, Tree, etc

• Can we have a recursive inline function in C++?


Even though it is possible to call an inline function from within itself in C++, the compiler may
not generate the inline code( as genrating or using the inline function is completely depends on
compiler and its choice). This is so because the compiler won’t determine the depth of the
recursion at the compile time.

Nonetheless, a compiler with a good optimizer is able to inline recursive calls until some depth
is fixed at compile-time and insert non-recursive calls at compile time for the cases when the
actual depth exceeds run time.

Oops :-
Object-oriented programming – As the name suggests uses objects in programming. The object-
oriented approach views a problem in terms of objects involved rather than procedure for
doing it. Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming.
• Object
Any real world entity is termed as an object. An Object is an instance of a Class. For ex, table,
chair, tv etc.

• Class
A Class is a user-defined data-type which has data members and member functions. A class is
like a blueprint for an object.

Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions define the
properties and behaviour of the objects in a Class.

In the example of class person, the data member will be name, id and member functions will be
get details.

• What is the difference between struct and class?


• Explain constructor in C++
The constructor is a member function that is executed automatically whenever an object is
created. Constructors have the same name as the class of which they are members so that
compiler knows that the member function is a constructor. And no return type is used for
constructors.

• What is a copy constructor?


A copy constructor is a member function that initializes an object using another object of the
same class. We can define our copy constructor. If we don’t define a copy constructor then the
default copy constructor is called.

• What is shallow copy & Also differentiate between shallow & deep copy.
Shallow Copy:

In shallow copy, an object is created by simply copying the data of all variables of the original
object. This works well if none of the variables of the object are defined in the heap section of
memory. If some variables are dynamically allocated memory from heap section, then copied
object variable will also reference then same memory location.

This will create ambiguity and run-time errors dangling pointer. Since both objects will
reference to the same memory location, then change made by one will reflect those change in
another object as well. Since we wanted to create a replica of the object, this purpose will not
be filled by Shallow copy.

Note: C++ compiler implicitly creates a copy constructor and overloads assignment operator in
order to perform shallow copy at compile time.
• What are destructors in C++?
A constructor is automatically called when an object is first created. Similarly when an object is
destroyed a function called destructor automatically gets called. A destructor has the same
name as the constructor (which is the same as the class name) but is preceded by a tilde.
• Static Keyword in C++
Static elements are allocated storage only once in a program lifetime in static storage area. And
they have a scope till the program lifetime. Static Keyword can be used with following,

1. Static variable in functions

2. Static Class Objects

3. Static member Variable in class

4. Static Methods in class

Static variables when used inside function are initialized only once, and then they hold there
value even through function calls.

These static variables are stored on static storage area , not in stack.

Example :-

Let's se the same program's output without using static variable.


• Encapsulation
Encapsulation is defined as binding together the data and the functions that manipulate them.
In normal terms, Encapsulation is defined as wrapping up of data and information under a
single unit.

Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section etc. Now there may arise a situation when for
some reason an official from the finance section needs all the data about sales in a particular
month. In this case, he is not allowed to directly access the data of the sales section. He will first
have to contact some other officer in the sales section and then request him to give the
particular data. This is what encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name “sales section”. so
this wrapping of data in a section( class ) so that only person(member function or methods)
from that section can manipulate data( data member or variables ) is called encapsulation.
In the above program the variable a is made private. This variable can be accessed and
manipulated only using the functions get() and set() which are present inside the class. Thus we
can say that here, the variable a and the functions get() and set() are binded together which is
nothing but encapsulation.

Note :- Encapsulation also known as data hiding because using encapsulation also hides the
data. In the above example, the data of any of the section like sales, finance or accounts are
hidden from any other section.

Role of access specifiers in encapsulation

As we have seen in above example, access specifiers plays an important role in implementing
encapsulation in C++. The process of implementing encapsulation can be sub-divided into two
steps:

1. The data members should be labeled as private using the private access specifiers

2. The member function which manipulates the data members should be labeled as public using
the public access specifier

• Access modifiers/specifiers
There are 3 types of access modifiers available in C++:

1. Public: All the class members declared under the public specifier will be available to
everyone. The data members and member functions declared as public can be accessed by
other classes and functions too. The public members of a class can be accessed from anywhere
in the program using the direct member access operator (.) with the object of that class.

2. Private: The class members declared as private can be accessed only by the member
functions inside the class. They are not allowed to be accessed directly by any object or
function outside the class. Only the member functions or the friend functions are allowed to
access the private data members of a class.

3. Protected: Protected access modifier is similar to private access modifier in the sense that it
can’t be accessed outside of it’s class unless with the help of friend class, the difference is that
the class members declared as Protected can be accessed by any subclass(derived class) of that
class as well.
• Friend class & function in C++ .
Friend Class A friend class can access private and protected members of other class in which it
is declared as friend. It is sometimes useful to allow a particular class to access private
members of other class. For example, a LinkedList class may be allowed to access private
members of Node.

Friend Function Like friend class, a friend function can be given a special grant to access private
and protected members. A friend function can be:

a) A member of another class

b) A global function

For example consider the friend class & function by GFG.

• Abstraction
Abstraction means displaying only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car but he does
not know about how on pressing accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of accelerator, brakes etc in the
car. This is what abstraction is.
- Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps
us to group data members and member functions using available access specifiers. A Class can
decide which data member will be visible to the outside world and which is not.

- Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need to
calculate the power of a number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
In the this example, we can see that abstraction has achieved by using class. The class
'Summation' holds the private members a, b and c, which are only accessible by the member
functions of that class.

• Difference Between Encapsulation & Abstraction.


Let us understand this with an example, You know you can communicate with your touch
phone through the screen( Abstract class or interface) provided to you which is hiding the
acutal implemtation behind it. This is abstraction but the details(circuits & connections) you
don't care about is still there and are hidden or encapsulated( by binding up it all together and
covering it( through aceess modifiers) so that it couldn't be accessed by any non
professional.)To access those circuits you will need small screw drivers( getters & setters ) .

Note :- Here Both screen(class or interface) & covering(access modifiers) over circuit are hiding
something but in a differenr aspect. In abstraction, problems are solved at the design or
interface level. While in encapsulation, problems are solved at the implementation level. So,
Abstraction is used also for hiding something but in a higher degree(class, interface).
Abstraction is done using abstract class or interfaces while encapsulation is done by using
access modifiers. In abstraction, implementation complexities are hidden using abstract
classes and interfaces. While in encapsulation, the data is hidden using methods of getters
and setters.

• Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.

A person at the same time can have different characteristic. Like a man at the same time is a
father, a husband, an employee. So the same person posses different behaviour in different
situations. This is called polymorphism.

An operation may exhibit different behaviours in different instances. The behaviour depends
upon the types of data used in the operation.

Note :- Polymorphism is extensively used in implementing inheritance

In C++ polymorphism is mainly divided into two types:


1. Compile time polymorphism:

This type of polymorphism is achieved by function overloading or operator overloading.

- Function Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by
change in number of arguments or/and change in type of arguments.

Rules & Examples of Function Overloading by GFG

- Operator Overloading: C++ also provide option to overload operators. For example, we can
make the operator (‘+’) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator ‘+’ when placed
between integer operands , adds them and when placed between string operands,
concatenates them.

Example of operator overloading by GFG.

2. Runtime polymorphism:

Suppose, the same function is defined in both the derived class and the based class. Now if we
call this function using the object of the derived class, the function of the derived class is
executed.

This is known as function overriding in C++. The function in derived class overrides the function
in base class.

Function overriding Example by JAVATPOINT


• Virtual Function in C++
A virtual function is a member function which is declared within a base class and is re-
defined(Overriden) by a derived class. When you refer to a derived class object using a pointer
or a reference to the base class, you can call a virtual function for that object and execute the
derived class’s version of the function.

- They are mainly used to achieve Runtime polymorphism.

- Functions are declared with a virtual keyword in base class.

- The resolving of function call is done at Run-time.

Rules for Virtual Functions

- Virtual functions cannot be static.

- A virtual function can be a friend function of another class.

- Virtual functions should be accessed using pointer or reference of base class type to achieve
run time polymorphism.

- The prototype of virtual functions should be the same in the base as well as derived class.

- They are always defined in the base class and overridden in a derived class. It is not mandatory
for the derived class to override (or re-define the virtual function), in that case, the base class
version of the function is used.

- A class may have virtual destructor but it cannot have a virtual constructor.

For code or ex :- Virtual function by C++ by GFG Do read the "concept of VTABLE and VPTR"
given at the end of the link.

• What is the difference between virtual functions and pure virtual functions?
A virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the virtual keyword.

Example-

class base{
public:

virtual void fun(){ }

};

A pure virtual function is a function that has no implementation and is declared by assigning 0.
It has no body.

Example-

class base{

public:

virtual void fun()=0;

};

Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything.
It is used to simply tell the compiler that a function will be pure and it will not have anybody.

• Pure Virtual Functions and Abstract Classes in C++


please consider this article by GFG.

• Can we call a virtual function from a constructor?


Yes, we can call a virtual function from a constructor. But the behavior is a little different in this
case. When a virtual function is called, the virtual call is resolved at runtime. It is always the
member function of the current class that gets called.

• Use of << and >> in C++ & can it be overloaded.


C++ is able to input and output the built-in data types using the stream extraction operator >>
and the stream insertion operator <<. The stream insertion and stream extraction operators
also can be overloaded to perform input and output for user-defined types like an object.
• Is constructor overloading possible? If yes then explain and if no then why?
Constructors can be overloaded in a similar way as function overloading. Overloaded
constructors have the same name (name of the class) but the different number of arguments.
Depending upon the number and type of arguments passed, the corresponding constructor is
called.

• Is deconstructor overloading possible? If yes then explain and if no then why?


No destructor overloading is not possible. Destructors take no arguments, so there’s only one
way to destroy an object. That’s the reason destructor overloading is not possible.

• Inheritance
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.

- Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.

- Super Class: The class whose properties are inherited by sub class is called Base Class or Super
class.

- Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Modes of Inheritance

- Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.

- Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.

- Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.

Note : The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed.

Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e.
one sub class is inherited by one base class only.

Syntax:

class subclass_name : access_mode base_class

//body of subclass

};

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from
more than one classes. i.e one sub class is inherited from more than one base classes.

Syntax:

class subclass_name : access_mode base_class1, access_mode base_class2, ....


{

//body of subclass

};

Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every
base class must be specified.

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.

4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited
from a single base class. i.e. more than one derived class is created from a single base class.

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one
type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
6. A special case of hybrid inheritance : Multipath inheritance: Diamond Problem

A derived class with two base classes and these two base classes have one common base class
is called multipath inheritance. An ambiguity can arrise in this type of inheritance.

For the example :- different types of inheritance in C++ by GFG

• What is the ‘diamond problem’ that occurs with multiple inheritance in C++?
Explain using an example.
The diamond problem occurs when two superclasses of a class have a common base class. For
example, in the following diagram, the TA class gets two copies of all attributes of Person class,
this causes ambiguities ( inexactness ).

The solution to this problem is ‘virtual’ keyword. We make the classes ‘Faculty’ and ‘Student’ as
virtual base classes to avoid two copies of ‘Person’ in ‘TA’ class.
For Code :- Diamond Problem by GFG.

• Static/Early Binding and Dynamic/Late Binding


Binding refers to the process of converting identifiers (such as variable and performance names)
into addresses. Binding is done for each variable and functions. For functions, it means that
matching the call with the right function definition by the compiler. It takes place either at
compile time or at runtime.
- Early Binding (compile-time time polymorphism) As the name indicates, compiler (or linker)
directly associate an address to the function call. It replaces the call with a machine language
instruction that tells the mainframe to leap to the address of the function.

- Late Binding : (Run time polymorphism) In this, the compiler adds code that identifies the
kind of object at runtime then matches the call with the right function definition (Refer this for
details). This can be achieved by declaring a virtual function.

For ex :- Early binding and Late binding in C++ by GFG

• Message Passing
Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function and the information to be sent.

The End

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy