0% found this document useful (0 votes)
24 views58 pages

C++ UNIT-4 New

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
24 views58 pages

C++ UNIT-4 New

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 58

C++ UNIT-4

C++ Basics : Overview, Program structure,


namespace, identifiers, variables, constants,
enum, operators, typecasting, control
Structures C++ Functions : Simple functions,
Call and Return by reference, Inline functions,
Macro Vs. Inline functions, Overloading of
functions, default arguments, friend
functions, virtual functions
Overview
C++ programming language was developed in
1980 by Bjarne Stroustrup at bell laboratories
of AT&T (American Telephone & Telegraph),
located in U.S.A.
Program structure
// C++ program to illustrate how create a simple class and
// object
#include <iostream>
#include <string>
using namespace std;
// Define a class named 'Person'
class Person {
public:
// Data members
string name;
int age;

// Member function to introduce the person


void introduce()
{
cout << "Hi, my name is " << name << " and I am "
<< age << " years old." << endl;
}
};
int main()
{
// Create an object of the Person class
Person person1;
// accessing data members
person1.name = "Alice";
person1.age = 30;
// Call the introduce member method
person1.introduce();
return 0;
}
Namespace in C++
Namespaces provide a method for preventing
name conflicts in large projects.
// A program to demonstrate need of namespace
int main()
{
int value;
value = 0;
double value; // Error here
value = 0.0;
}
In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the
same scope. Using namespaces, we can create two variables or member functions having the same name.

#include <iostream>
using namespace std;

// Variable created inside namespace


namespace first
{
int val = 500;
}

// Global variable
int val = 100;

int main()
{
// Local variable
int val = 200;

// These variables can be accessed from


// outside the namespace using the scope
// operator ::
cout << first::val << '\n';

return 0;
}
• A namespace is a declarative region that provides a scope to the identifiers (names
of the types, function, variables etc) inside it.
• Multiple namespace blocks with the same name are allowed. All declaration within
those blocks are declared in the named scope .
• A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
• Namespace declarations appear only at global
scope.
• Namespace declarations can be nested within
another namespace.
• Namespace declarations don’t have access
specifiers. (Public or private)
• No need to give semicolon after the closing
brace of definition of namespace.
// Creating namespaces
#include <iostream>
using namespace std;
namespace ns1
{
int value() { return 5; }
}
namespace ns2
{
const double x = 100;
double value() { return 2*x; }
}

int main()
{
// Access value function within ns1
cout << ns1::value() << '\n';

// Access value function within ns2


cout << ns2::value() << '\n';

// Access variable x directly


cout << ns2::x << '\n';

return 0;
}
Identifiers

Identifiers Are the programming elements


Like Variable name, function name, array
name, structure name, class name, object
name, pointer name……etc which is defined
by the Programmer
Rules for Identifiers
1. Allowed Characters are:
A-Z,a-z
0123456789
Underscore sign _

2. Should not start with digit.


3. Space is not allowed.
4. Keywords are not allowed.
5. Uppercase Letters (such as A B C…etc)and Lower
Case(such as a b c ….etc) letters are different.
Literals OR Constant in C++
Whose value can not be changed at the
execution time of program is called Constant
or Literals.
• Types of Integer constant
• Decimal integer constant
• Octal integer constant
• Hexadecimal integer constant
A sequence of digit starting with 0(zero) and make sure digit 8 or 9 is not
included is taken to be an octal integer constant.
055 ,023,05,0457
A sequence of digit starting with 0x or 0X is taken to be an Hexadecimal
integer constant.

Examples are: 0x123, 0X34d


2. Character Constant
If any single character (such as alphabet or numeric or special symbol) is
enclosed between single cotes (' ') known as single character constant.

char a=’d’; //’d’ is called character constant


chat a=’+’; //’+’ is called character constant

3. String Constant
If set of characters (such as alphabet or numeric or special symbol) are
enclosed between double cotes "" known as string character constant.
Example : “ abcd ”
“ tete3+-_=) ”

4. Floating Constant or real Constant


Real constants are number having factional parts.
Valid Real constant are:
2.0 , 17.52 , -13.25 , -0.00478
operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Sizeof
• Conditional operator (?)
• Comma operator
• Pointer operator &
• Pointer operator *
• Member operators
Conditional? Operator

#include <iostream.h>
#include<conio.h>
void main () {
// Local variable declaration:
int x, y = 10;
x = (y < 10) ? 30 : 40;
cout << "value of x: " << x << endl;
}
Output value of x:40
Member (dot & arrow) Operators
• The . (dot) operator and the -> (arrow)
operator are used to reference individual
members of classes, structures, and unions.
• To access members of a structure, use the dot
operator. To access members of a structure
through a pointer, use the arrow operator.
Comma Operator( , )
The purpose of comma operator is to combined
together several expressions.
#include <iostream.h>
#include<conio.h>
void main()
{
int i, j;
j = 10;
i = (j++, j+100, 999+j);
cout << i;
}
pointer & Address operators(& *)
C++ provides two pointer operators, which are

(a) Address of Operator &


(b) Indirection Operator *.

& is a unary operator that returns the memory


address of its operand

* It is a unary operator that returns the value of the


variable located at the address specified.
#include <iostream>
#include<conio.h>
Void main ()
{
int var;
int *ptr;
int val;
var = 3000;
// take the address of var
ptr = &var;

// take the value available at ptr


val = *ptr;
cout << "Value of var :" << var << endl;
cout << "Value of ptr :" << ptr << endl;
cout << "Value of val :" << val << endl;
}
Type conversion
There are two types of type conversion:
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion

• Done by the compiler.


• Also called automatic Type conversion.
All the data types of the variables are upgraded to the data type of the variable
with largest data type.

C++ compiler convert all operands upto the type of the largest operand ,which is
called Type Promotion.
/ An example of implicit conversion
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;

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


return 0;
}
Explicit Type Conversion
*also called Type casting.
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.
int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

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

return 0;
}

Output
Sum=2
Functions
Depending on whether a function is
predefined or created by programmer, there
are two types of functions:
1. Library Function (Predefined function)
2. User-defined Function (created by
programmer like you as per need
User define function has three
component
• Function declaration or function Prototype.
• Function call
• Function definition or function defining
1. 1.Function declaration Syntax
return_type function_name (list of argument);
1.return_type: return type specify, which type of
value return by function, like int float, double
,char..etc .
* If function not return any value we take void
*By default return type is integer
2. function_name: Function name is valid
identifies, This name use in function call.
3. List of argument: these are place holder in
memory(RAM)
2. Function call Syntax
To execute the logic of function definition, the
user-defined function needs to be call
inside void main() function.
3. Function definition
Function definition has two part

function header
1. function header (which is same as function
declaration)
2. function body
1. #include < iostream.h>
2. #include<conio.h>
3. using namespace std;
4. int sumt (int x, int y); //declaring function
5. void main()
6. {
7. int a = 10;
8. int b = 20;
9. int d = sumt (a, b); // function call / control is transfer //to function
definition and a ,b value is transfer to x,y
10. cout << d;
11. }
12. int sumt (int x, int y) //defining function
13. {
14. int c;
15. c=x+y;
16. return (c);
17. }
exit() vs return()
Return : Transfer control to calling function.
Exit(): terminate the entire program and control
is transfer to OS itself.

exit()– stdlib.h & process.h


Types of User-defined Functions in
C++
• Function with no argument and no return
value
• Function with no argument but return value
• Function with argument but no return value
• Function with argument and return value
Call by Value, Call by Reference
• This method copies the value of an argument
into the formal parameter.
• address of an argument is copied into the
parameter.
Call by Value
#include<iostream.h>
using namespace std;
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void main()
{
int x=25, y=50;
clrscr();
swap(x, y); // passing value to function
cout<<"The Value of x: "<<x;
cout<<"The Value of y: "<<y;
}
Call by reference
#include<iostream.h>
using namespace std;
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
cout<<"Value of a"<<a;

cout<<"Value of b"<<b;
}
Inline function
C++ provides an inline functions to reduce the
function call overhead.
When the inline function is called whole code of the
inline function gets inserted or substituted at the
point of inline function call.
Code substitution is performed by the C++ compiler
at compile time.
Compiler may not perform inlining in
such circumstances like:

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


while)
2) If a function contains static variables.
3) If a function is recursive.
4) function with a return statement but do not
returns values.
5) If a function contains switch or goto
statement.
Inline functions
advantages/Disadvantage
It also saves the overhead of push/pop
variables on the stack .
If you use too many inline functions then the
size of the binary executable file will be large,
because of the duplication of same code.
#include <iostream>
inline void operation :: difference()
using namespace std;
{
class operation sub = a-b;
{ cout << "Difference of two numbers: " << a-b <<
int a,b,add,sub,mul; "\n";
float div; }
public:
void get(); inline void operation :: product()
void sum(); {
void difference(); mul = a*b;
void product(); cout << "Product of two numbers: " << a*b <<
void division(); "\n";
}
};
inline void operation ::division()
inline void operation :: get()
{
{ div=a/b;
cout << "Enter first value:"; cout<<"Division of two numbers: "<<a/b<<"\n" ;
cin >> a; }
cout << "Enter second value:"; int main()
cin >> b; {
} cout << "Program using inline function\n";
operation s;
inline void operation :: sum() s.get();
{ s.sum();
add = a+b; s.difference();
s.product();
cout << "Addition of two numbers: " << a+b << "\n";
s.division();
} return 0;
}
Macro vs inline function
inline macro
An inline function is defined by Whereas the macros are defined by
the inline keyword. the #define keyword.
An inline function is a short function that Before the program compilation, the
is expanded by the compiler. preprocessor examines the program
whenever the preprocessor detects the
macros then preprocessor replaces the
macro by the macro definition.
In C++, inline may be defined either inside Whereas the macro is all the time defined
the class or outside the class. at the beginning of the program.
Inline function is terminated by the curly While the macro is not terminated by any
brace at the end. symbol, it is terminated by a new line.
In the case of inline function, the program Whereas in the case of macros, the
can be easily debugged. program can’t be easily debugged.
Function Overloading
The term Polymorphism refers to one name having many
forms .Polymorphism is the one most important features in
C++. We achieve polymorphism in C++ by function
overloading and function overriding(used in inheritance
concept) .

C++ Implements overloading through-


• Function overloading
• Operators overloading
Function overloading
Function overloading means function having
same name but type of argument and
number of argument are different.

following four functions are called overloaded


in C++.
Note : Function overloading are also called Static binding or
early binding .Because function call resolve at compilation
time .

Whereas function Overriding are called dynamic binding or


run time binding (discuss later in inheritance concept).
#include<iostream.h> void printsquare(float f)
void printsquare(int i); {
void printsquare(char c); cout<<"Float "<<f<<"'s square is "<<f*f<<"\n";
void printsquare(float f); }
void main()
{
clrscr(); printsquare(50);
printsquare(‘A’);
printsquare(50.60);
}
void printsquare(int i)
{
cout<<"Integer "<<i<<"'s square is "<<i*i<<"\n";
}
void printsquare(char c)
{
cout<<c<<" is a character "<<"Thus No Square for
it"<<"\n";
}
Default argument
. Function Overloading

Function overloading allows you to have multiple functions with the same name but different parameter lists in the same scope. The compiler
determines which function to call based on the number and types of arguments passed.

#include <iostream>
using namespace std;
class Person {
public:
// Overloaded functions
void greet() {
cout << "Hello!" << endl;
}
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
void greet(string name, int age) {
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
}
};
int main() {
Person p;
p.greet(); // Calls greet()
p.greet("Alice"); // Calls greet(string name)
p.greet("Alice", 30); // Calls greet(string name, int age)
return 0;
}

In this example, greet is overloaded. Depending on the arguments passed, different versions of greet are called.

2. Function Overriding

Function overriding allows a derived class to provide a specific implementation of a function that is already defined in its base class. This is
achieved with inheritance and requires the virtual keyword in the base class.
cpp
Copy code
#include <iostream>
using namespace std;

class Person {
public:
virtual void displayInfo() {
cout << "Person Info: This is a person." << endl;
}
};

class Student : public Person {


public:
void displayInfo() override { // Overrides displayInfo in base class
cout << "Student Info: This is a student." << endl;
}
};

int main() {
Person p;
Student s;
p.displayInfo(); // Calls Person's displayInfo()
s.displayInfo(); // Calls Student's displayInfo()
Person* personPtr = &s;
personPtr->displayInfo(); // Calls Student's displayInfo() due to polymorphism
return 0;
}

In this example, displayInfo is overridden in the Student class. The virtual keyword in the base class allows polymorphism, so calling
displayInfo on a Person pointer to a Student object will use the Student version.

3. Friend Function
A friend function is a function that is not a member of a class but has access to its private and protected members. You declare it with the
friend keyword inside the class.

#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
// Declaring a friend function
friend void showPersonInfo(const Person &p);
};

// Friend function definition


void showPersonInfo(const Person &p) {
cout << "Name: " << p.name << ", Age: " << p.age << endl;
}

int main() {
Person p("Alice", 30);
showPersonInfo(p); // Calls the friend function

return 0;
}

In this example, showPersonInfo is a friend function of the Person class. It has access to Person's private members name and age, even though
it is not a member function. This is useful when you want certain external functions to access private data directly.

Summary

• Function Overloading: Same function name, different parameters.


• Function Overriding: Redefining a base class's function in a derived class.
• Friend Function: Non-member function with access to private members.

You might also like