0% found this document useful (0 votes)
4 views24 pages

C++important Ques Ans

The document discusses various control structures in C++, including sequence, selection, and iteration logic. It covers topics such as inline functions, nested member functions, function overloading, constructors, stream classes, file handling operations, and constant member functions. Additionally, it explains copy constructors and operator overloading with examples.

Uploaded by

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

C++important Ques Ans

The document discusses various control structures in C++, including sequence, selection, and iteration logic. It covers topics such as inline functions, nested member functions, function overloading, constructors, stream classes, file handling operations, and constant member functions. Additionally, it explains copy constructors and operator overloading with examples.

Uploaded by

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

PART B

1. Discuss the control structures in C++


There are three types of control structures:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow
1. Sequential Logic (Sequential Flow)
Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the
series of instructions given to the computer.

Selection Logic (Conditional Flow)


Selection Logic simply involves a number of conditions or parameters which decides one out of several written
modules. The structures which use these type of logic are known as Conditional Structures. These structures
can be of three types:
Nested if-else Statements: In this kind of statement, a number of logical conditions are tested for taking
decisions. Here, the if keyword followed by an expression is evaluated. If it is true, the compiler executes the
block following the if condition; otherwise, it skips this block and executes the else block. It uses the if
statement nested inside an if-else statement, which is nested inside another if-else statement. This kind of
nesting can be limitless.
if(condition1)
{
// Code to be executed
if(condition2)
{
// Code to be executed
}
else
{
// Code to be executed
}
}
else
{
// code to be executed
}
The else-if Ladder: A common programming construct is the else-if ladder, sometimes called the if-else-if staircase
because of its appearance. In the program one can write a ladder of elseif. The program goes down the ladder of
else-if, in anticipation of one of the expressions being true.

Unconditional Control Transfer Statements The goto statement: This statement does not require any condition. This
statement passes control anywhere in the program without considering any condition. The general format for this
statement is shown in figure. Here, a label is any valid label either before or after goto. The ‘label’ must start with
any character and can be constructed with rules used for forming identifiers. Avoid using the goto statement.
Syntax:
goto label;
----- ----- -----
label:
The break Statement:
The break statement allows the programmer to terminate the loop. The break skips from the loop or the
block in which it is defined.
Break;
continue statement works somewhat like the break statement. Instead of forcing the control to the end of the loop
(as it is in case of break), the continue case causes the control to pass on to the beginning of the block/loop. In the
case of for loop, the continue case initiates the testing condition and increment on steps has to be executed.

2. Write a c++ program for inline function


C++ provides inline functions to reduce the function call overhead. An inline function is a function that is
expanded in line when it is called. When the inline function is called whole code of the inline function gets
inserted or substituted at the point of the inline function call. This substitution is performed by the C++
compiler at compile time. An inline function may increase efficiency if it is small.

Syntax:

inline return-type function-name(parameters)

// function code

program
The compiler may not perform inlining in such circumstances as:

 If a function contains a loop. (for, while and do-while)

 If a function contains static variables.

 If a function is recursive.

 If a function return type is other than void, and the return statement doesn’t exist in a function body.

 If a function contains a switch or goto statement.

3. Write a program for nested member function


A member function can be called by using its name inside another member function of the same class. This
is known as nesting of member functions.

# include <iostream.h>
class set {
int m , n; public:
void input (void);
void display (void);
int largest (void );
};

int set :: largest (void ) {


if ( m >=n )
return (m);
else
return (n);
}

void set :: input (void ) {


cout << “ input values of m and n “ << “\n” ;
cin >> m >> n ;
}
void set :: display (void ){
cout <<”largest value = “ << largest ( ) << “\n”;
}
main ( ) {
set A ;
A. input ( );
A. display ( );
}

The output of program would be:


Input values of m and n 30 17
largest value = 30

4. Function overloading with example


Function overloading is a feature of object-oriented programming where two or more functions can have the same
name but different parameters. When a function name is overloaded with different jobs it is called Function
Overloading.

In Function Overloading “Function” name should be the same and the arguments should be different. It is an
example of a polymorphism in C++.

#include<iostream.h>
#include<conio.h>
void display(int no1,double no2)
{
cout<<"integer number:"<<no1;
cout<<"and double number:"<<no2;
}
void display(double no)
{
cout<<"double number:"<<no;
}
void display(int no)
{
cout<<"integer number:"<<no;
}
int main()
{
int a=5;
double b=55;
display(a);
display(b);
display(a,b);
return 0; }

5. What are constructors how they differ from member functions


Constructor in C++ is a special member function of a class which is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same
name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as
constructor.
Difference between constructor and member function

1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class. Member function needs to be called
explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates a default constructor and insert it
into our code. The same does not apply to member functions.

6.Stream classes in C++


In C++ there are number of stream classes for defining various streams related with files and for doing input-
output operations. All these classes are defined in the file iostream.h.

1. ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.

2. istream and ostream serves the base classes for iostream class. The class istream is used for input
and ostream for the output.

3. Class ios is indirectly inherited to iostream class using istream and ostream.
4. The ios class: The ios class is responsible for providing all input and output facilities to all other stream
classes.
5. The istream class: This class is responsible for handling input stream. It provides number of function for
handling chars, strings and objects such as get, getline, read, ignore, putback etc..
Example
#include <iostream>
using namespace std;

int main()
{
char x;

// used to scan a single char


cin.get(x);

cout << x;
}
The ostream class: This class is responsible for handling output stream. It provides number of function for handling
chars, strings and objects such as write, put etc..
Example:
#include <iostream>
using namespace std;

int main()
{
char x;

// used to scan a single char


cin.get(x);

// used to put a single char onto the screen.


cout.put(x);
}

7.Any four operations related to file


Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output
of a program in a file and perform various operations on it.
In C++ we have a set of file handling functions. These are ifstream, ofstream, and fstream. These classes are
derived from fstreambase and from the corresponding iostream class. These classes, designed to manage the disk
files, and are declared in fstream, therefore we must include fstream in every program that uses files.
C++ offers us the following operations in File Handling:
 open():Creating a file
 read():**Reading data

 write():Writing new data

 close():Closing a file

Opening a file
We can open a file using one of the following methods:
 bypassing the file name in constructor at the time of object creation.
 using the open() function.

Syntax to open a file


void open(const char* fileName,ios::openMode mode);
The first argument of the open function is the name and format of the file along with the address of the file.
The second argument represents the mode in which the file has to be opened.
Example
fstream newFile; newFile.open("newfile.txt", ios::out);
Writing to a File

First create a new file “new_filewrite” using open() function as we want to send output to the file we use ios::out.
The information we type inside the quotes after Insertion Pointer “<<” gets passed to the output file.

#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file) {
cout<<"File creation failed"; }
else {
cout<<"New file created";
new_file<<"Learning File handling";
new_file.close(); }
return 0;

Output: New file created


Reading from the file
We read the file that is generated in the previous example i.e. new_filewrite. To read a file we make use of the in
mode with syntax ios::in. We print the content of the file using extraction operator `>>`. The output prints without
any space because we use only one character at a time, we need to use getline() with a character array to print the
whole line as it is.
int main() {
fstream newFile; newFile.open("new_filewrite.txt",ios::in);
if(!newFile) {
cout<<"No such file"; }
else {
char ch;
while (!newFile.eof()) {
newFile >>ch; cout << ch; }
newFile.close(); }
return 0; }
Output: LEARNFILEHANDLINGG
Closing a file
Once we are done using a file in a C++ program use the close() function to close the file.
int main() {
fstream newFile;
newFile.open("newFile.txt",ios::out);
newFile.close(); return 0; }
The file gets closed!!
8.File pointers and their manipulations
A pointer is used to handle and keep track of the files being accessed. Every file maintains two pointers called
get_pointer (in input mode file) and put_pointer (in output mode file), which tells the current position where
reading or writing will take place with the use of opening modes and their respective manipulators.
Functions of file handling:
seekg():-
It is used to move the get pointer to the desired location concerning a reference point.
Syntax: file_pointer.seekg (number of bytes ,Reference point);
Example: fin.seekg(10,ios::beg);
tellg():-
tellg() is used to realize which they get pointer is in a file.
Syntax: file_pointer.tellg();
Example: int posn = fin.tellg();
seekp():-
seekp() is used to move the put pointer to the desired location concerning a reference point.
Syntax: file_pointer.seekp(number of bytes ,Reference point);
Example: fout.seekp(10,ios::beg);
tellp():-
tellp()is used to realize which they get pointer is in a file.
Syntax: file_pointer.tellp();
Example: int posn=fout.tellp();
Manipulators are helping functions that can modify the input/output stream. It does not mean that we
change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators.
Types of Manipulators
There are various types of manipulators:

Manipulators without arguments: The most important manipulators defined by the IOStream library are provided
below.

endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all
the output written on the screen or in the file) the output stream.
ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.

ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with
std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.

flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen
or in the file. Without flush, the output would be the same, but may not appear in real-time.

#include <iostream>
#include <istream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
istringstream str(" Challenging");
string line;
getline(str >> std::ws, line);
cout << line << endl;
cout << "only an example" << flush;
cout << "\nc";
cout << "a" << ends;
cout << "t" << endl;
return 0;
}
The read operation from a file involves getting a pointer. It points to a specific location in the file and the reading
starts from that location.
Then, the get pointer keeps moving forward which lets us read the entire file. Similarly, we can start
writing to a location where the put pointer is currently pointing. The get and put are known as file position pointers
and these pointers can be manipulated or repositioned to allow random access to the file.

9.Structure of C++
Example program
#include<iostream.h>
#include<conio.h>
void display(int var1, double var2) {
cout<<"Integer number:"<<var1;
cout<<"and double number:"<<var2; }
void display(double var) {
cout<<"Double number:"<<var; }
void display(int var) {
cout<<"Integer number:"<<var; }
int main(){
int a=5;
double b=5.5;
display(a);
display(b);
display(a,b);
return 0; }

10.What is constant member function


Constant member functions are those functions that are denied permission to change the values of the data
members of their class. To make a member function constant, the keyword const is appended to the function
prototype and also to the function definition header.
An object declared as const cannot be modified and hence, can invoke only const member functions as
these functions ensure not to modify the object.
Syntax
The const member function can be defined in three ways:

1. For function declaration within a class.


return_type function_name() const;
int get_data() const;
2. For function definition within the class declaration.
return_type function_name () const
{
//function body
}
Example:

int get_data() const


{
//function body
}
3. For function definition outside the class.
return_type class_name::function_name() const
{
//function body
}
Example:

int Demo :: get_data() const


{
}
 When a function is declared as const, it can be called on any type of object.
 Whenever an object is declared as const, it needs to be initialized at the time of declaration.
 A function becomes const when the const keyword is used in the function’s declaration.
Example program
#include <iostream.h>
class Demo {
int x;
public:
void set_data(int a) { x = a; }
int get_data() {
++x;
return x;}
};
main() {
Demo d;
d.set_data(10);
cout << d.get_data();
return 0; }
11.Write short notes on copy constructor
A copy constructor is a member function that initializes an object using another object of the same class. In simple
terms, a constructor which creates an object by initializing it with an object of the same class, which has been
created previously is known as a copy constructor.
• Copy constructor is used to initialize the members of a newly created object by copying the members of an
already existing object.
• Copy constructor takes a reference to an object of the same class as an argument.
Syntax
Class_name(class_name &object_name)
{
// body of the constructor.
}
Program
#include <iostream.h>
class Sample {
int id;
public:
void init(int x) { id = x; }
void display() { cout << endl << "ID=" << id; }
};
int main() {
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1);
obj2.display();
return 0;
}

12.Write a program segment that overloads ++ operator or unary operator


overloading
C++ provides a special function to change the current functionality of
some operators within its class which is often called as operator
overloading.
Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function

C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator
overloading. Operator overloading is a compile-time polymorphism. For example, we can overload an operator ‘+’
in a class like String so that we can concatenate two strings by just using +.
class Count {
private:
int value;
public:
Count() : value(5) {}
void operator ++ () {
++value;
}
void display() {
cout << "Count: " << value << endl;
} };
int main() {
Count count1;
++count1;
count1.display();
return 0; }

13.How to make private member inheritable


The private members of a class can be inherited but cannot be accessed directly by its derived classes. They
can be accessed using public or protected methods of the base class.
#include <iostream.h>
class Base {
private:
int pvt = 1;
public:
int pub = 2;
int getPVT() {
return pvt;
} };
class Derived : private Base {
public:
int getPub() {
return pub;
} };
int main() {
Derived object1;
cout << "Private cannot be accessed." << endl;
cout << "Public = " << object1.getPub() << endl;
return 0; }

14.Write note on unformatted I/O operation


Using objects cin and cout for the input and the output of data of various types is possible because
of overloading of operator >> and << to recognize all the basic C++ types. The operator >> is overloaded in
the istream class and operator << is overloaded in the ostream class.
The general format for reading data from the keyboard:
cin >> var1 >> var2 >> …. >> var_n;
 Here, var1, var2, ……, varn are the variable names that are declared already.
 The input data must be separated by white space characters and the data type of user input must be similar
to the data types of the variables which are declared in the program.
 The operator >> reads the data character by character and assigns it to the indicated location.
 Reading of variables terminates when white space occurs or character type occurs that does not match the
destination type.
Program 1:
#include <iostream.h>
int main()
{
int data;
char val;
cin >> data;
cin >> val;
cout << data << " " << val;
return 0; }
put() and get() functions:
The class istream and ostream have predefined functions get() and put(), to handle single character input and
output operations. The function get() can be used in two ways, such as get(char*) and get(void) to fetch characters
including blank spaces, newline characters, and tab. The function get(char*) assigns the value to a variable
and get(void) to return the value of the character.
Syntax:
char data;
data = cin.get();
cout.put(data);
Example:
char c;
cin.get(c);
cout.put()
#include <iostream.h>
// Driver Code
int main() {
char data;
int count = 0;
cout << "Enter Data: ";
// Get the data
cin.get(data);
while (data != '\n') {
cout.put(data);
count++;
cin.get(data);
}
return 0; }

getline() and write() functions:


In C++, the function getline() and write() provide a more efficient way to handle line-oriented inputs and
outputs. getline() function reads the complete line of text that ends with the new line character. This function can
be invoked using the cin object.
Syntax:
cin.getline(variable_to_store_line, size);
The reading is terminated by the ‘\n’ (newline) character. The new character is read by the function, but it does
not display it, instead, it is replaced with a NULL character. After reading a particular string the cin automatically
adds the newline character at end of the string.
The write() function displays the entire line in one go and its syntax is similar to the getline() function only that
here cout object is used to invoke it.
Syntax:
cout.write(variable_to_store_line, size);
The key point to remember is that the write() function does not stop displaying the string automatically when
a NULL character occurs. If the size is greater than the length of the line then, the write() function displays
beyond the bound of the line.

15.Command Line Argument in C++


Command-line arguments are arguments that are passed to a program when it is executed from the
command line or terminal. They are provided in the command-line shell of operating systems with the program
execution command.
The main function of C++ generally can have the following signature:
int main(){
// Suitable Code
return 0;
}
But to pass command-line arguments, we typically define main() with two arguments, where the first argument is
the number of command-line arguments and the second is the list of command-line arguments.
Signature of main() Function for C++ Command Line Arguments
int main(int argc, char *argv[]){
// Suitable Code
return 0;
}
What is argc?
The variable argc (ARGument Count) is an integer that stores the number of command line arguments passed to
the main function. It also includes the count for the name of the program, so if we pass a value to a program, the
value of argc would be 2 (one for argument and one for program name).
What is argv?
The array argv (ARGument Vector) is an array of C-style strings like (‘char*’) where every element
points to a command line argument. argv does not store the actual argument, but the pointer to that
argument. The argv[0] will always contain the name of the program.
#include <iostream.h>
int main(int argc, char* argv[])
{
cout << "You have entered " << argc<< " arguments:" << endl;
int i = 0;
while (i < argc) {
cout << "Argument " << i + 1 << ": " << argv[i]
<< endl;
i++;
}
return 0; }

Input
./program1 hello geeks
Output
You have entered 3 arguments:
Argument 1: ./program1
Argument 2: hello
Argument 3: geeks
Properties of Command Line Arguments in C++
 The argc is an integer that stores the number of command line arguments.
 The argv store is an array of pointers to characters that stores the command line arguments.
 The first element in argv (argv[0]) contains the name of the program itself.
 Only string values are passed through the command line argument.
 Multiple arguments are separated by a whitespace. To pass a single argument with some
whitespace, we use
 The argv[1] points to the first command line argument and argv[argc-1] points to the last
argument. argv[argc] is NULL.

16.User defined data types


Data types are means to identify the type of data and associated operations of handling it.
improve. In C++ datatypes are used to declare the variable. There are three types of data
types:
 Pre-defined DataTypes
 Derived Data Types
 User-defined DataTypes

User-Defined DataTypes
The data types that are defined by the user are called the derived datatype or user-defined
derived data type. These types include:
 Class
 Structure
 Union
 Enumeration
1. Class
A Class is the building block of C++ that leads to Object-Oriented programming is
a Class. It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is
like a blueprint for an object.

Syntax
2. Structure
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.
Syntax
struct structName{
char varName[size];
int varName;
};
3. Union
Like Structures , Union a user-defined data type. In union, all members share the same
memory location. For example in the following C program, both x and y share the same
location. If we change x, we can see the changes being reflected in y.
Syntax
Union_Name
{
// Declaration of data members
}; union_variables;
4. Enumeration
Enumeration (or enum) is a user-defined data type in C. It is mainly used to assign names
to integral constants, the names make a program easy to read and maintain.
Syntax
enum nameOfEnum {
varName1 = 1, varName2 = 0
};
5. Typedef
C++ allows you to define explicitly new data type names by using the keyword typedef.
Using typedef does not create a new data class, rather it defines a name for an existing
type. This can increase the portability(the ability of a program to be used across different
types of machines; i.e., mini, mainframe, micro, etc; without many changes to the code)of
a program as only the typedef statements would have to be changed. Using typedef one
can also aid in self-documenting code by allowing descriptive names for the standard data
types.
Syntax
typedef typeName;
where typeName is any C++ data type and name is the new name for this data type. This
defines another name for the standard type of C++.

17. What are the ways the constructor can be called


There are 3 types of constructors in C++, They are :
 Default Constructor
 Parameterized Constructor
 Copy Constructor
Syntax of Constructors in C++
<class-name> (list-of-parameters);
The constructor can be defined inside the class declaration or outside the class declaration
Syntax for Defining the Constructor Within the Class
<class-name> (list-of-parameters)
{
// constructor definition
}
Syntax for Defining the Constructor Outside the Class
<class-name>: :<class-name>(list-of-parameters)
{
// constructor definition
}
1. Default Constructor in C++
A default constructor is a constructor that doesn’t take any argument. It has no parameters.
It is also called a zero-argument constructor.
Syntax of Default Constructor
className() {
// body_of_constructor
}
2. Parameterized Constructor in C++
Parameterized Constructors make it possible to pass arguments to constructors. Typically,
these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function. When
you define the constructor’s body, use the parameters to initialize the object.
Syntax of Parameterized Constructor
className (parameters...) {
// body
}
3. Copy Constructor in C++
A copy constructor is a member function that initializes an object using another object of
the same class.
Syntax of Copy Constructor
Copy constructor takes a reference to an object of the same class as an argument.
ClassName (ClassName &obj)
{
// body_containing_logic
}
18.Single Inheritance
In single inheritance, a class derives from one base class only. This means that there is
only one subclass that is derived from one superclass. The capability of a class to derive
properties and characteristics from another class is called Inheritance.

class subclass_name : access_mode base_class


{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
#include<iostream.h>
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
class Car : public Vehicle {

};
int main()
{
Car obj;
return 0;
}

19.Formatted I/O in C++


C++ helps you to format the I/O operations like determining the number of digits to be displayed after
the decimal point, specifying number base etc.
 If we want to add + sign as the prefix of out output, we can use the formatting to do so:
stream.setf(ios::showpos)
If input=100, output will be +100
 If we want to add trailing zeros in out output to be shown when needed using the formatting:
stream.setf(ios::showpoint)
If input=100.0, output will be 100.000
Formatting using ios functions
The ios class contains a number of functions that can be used to set/unset the formatting flags and
perform other tasks using format state variables.

First three functions can be used to set the value of the format state variables with specified argument and
they all return the old the value of the corresponding variable. For example, w=width(5); sets the value of
format state variable width to 5 and returns its old value.These functions can also be used without
specifying argument. In this case, it simply returns the value of the format state variables. Ex. w=width();
returns the value of width.Functions setf() and unsetf() takes bits of format flags as arguments and
set/unset corresponding bits.

20.Different modes in files can be opened in C++


Opening a file is done using the fopen() function in the header file stdio.h.
Syntax:
fptr = fopen(“file_name”, “mode”);
21.Benefits of OOP

22. How to define member function in class

A class member function is a function that, like any other variable, is defined or
prototyped within the class declaration. It has access to all the members of the
class and can operate on any object of that class.
There are 2 ways to define a member function:
• Inside class definition
• Outside class definition
• To define a member function outside the class definition we have to use the scope
resolution:: operator along with the class name and function name.
#include <iostream.h>

class Room {

public: // access specifier

double length; double breadth; double height; // data member

double calculateArea() // member function {

return length * breadth;

double calculateVolume()

{
return length * breadth * height; }

};
int main() {

Room room1; // create object of Room class

room1.length = 42.5; room1.breadth = 30.8; room1.height = 19.2;

cout << "Area of Room = " << room1.calculateArea() << endl;

cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0; }
member function outside the class
• The member function is defined outside the class definition it can be defined using
the scope resolution operator. Similar to accessing a data member in the class we
can also access the public member functions through the class object using the dot
operator (.).

23 . Type Conversion in C++


A type cast is basically a conversion from one type to another. There are
two types of type conversion:
1. 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 lose of data.
 All the data types of the variables are upgraded to the data type
of the variable with largest data type.
bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double



 It is possible for implicit conversions to lose information, signs
can be lost (when signed is implicitly converted to unsigned), and
overflow can occur (when long long is implicitly converted to float).
Example of Type Implicit Conversion:

// An example of implicit conversion

#include <iostream>
using namespace std;

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int.


ASCII
// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}

Output:
x = 107
y = a
z = 108
2. Explicit Type Conversion: This process is also called type casting
and it is user-defined. Here the user can typecast the result to make it
of a particular data type.
In C++, it can be done by two ways:
3.
 Converting by assignment: This is done by explicitly defining
the required type in front of the expression in parenthesis. This can be
also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:

// C++ program to demonstrate


// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to


int
int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

Output:
Sum = 2

You might also like