0% found this document useful (0 votes)
28 views

3 Oop

Uploaded by

nogati3383
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

3 Oop

Uploaded by

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

A.D.

PATEL INSTITUTE OF TECHNOLOGY


(A Constituent College of CVM University)

Subject: Object Oriented Programming(102000212)


C++ Basics
Contents /Topics to be covered
• Overview of C++
• Program structure
• namespace
• identifiers
• variables
• constants
• enum
• operators
• typecasting
• control structures
Overview of C++

• C ++ is an object oriented programming language, C ++ was developed by


Bjarne Stroustrup at AT & T Bell lab, USA in early eighties.

• C ++ was developed from c and simula 67 language.

• C ++ was early called ‘C with classes’.


Comments
• A comment may start anywhere in the line and whatever follows till the end
of line is ignored.

• Note that double slash comment is basically a single line comment.

• // thank you

• Multi line comments can be written as follows:

• The c comment symbols /* ….*/ are still valid and more suitable for multi
line comments.

• /* this is an example of c++ program */


C++ Console I/O (Input)

6
Input Operator:
• The statement cin >> number1; is an input statement and causes the
program to wait for the user to type in a number.

• The number keyed in is placed in the variable number1.

• The identifier cin is a predefined object in C++ that corresponds to the


standard input stream.

• The operator >> is known as get from operator.

• It extracts value from the keyboard and assigns it to the variable on its
right.
C++ Console I/O (Input)
• cin >> strName; /* char strName[16] */
• scanf(“%s”, strName);
• cin >> iCount; /* int iCount */
• scanf(“%d”, &iCount);
• cin >> fValue; /* float fValue */
• scanf(“%f”, &fValue);
• In general, cin >> variable;

8
C++ Console I/O (Output)
Output Operator
• The statement cout << ”Hello, world” displayed the string with in quotes on
the screen.
• The identifier cout can be used to display individual characters, strings and
even numbers.
• It is a predefined object that corresponds to the standard output stream.
• Stream just refers to a flow of data and the standard Output stream
normally flows to the screen display.
• The cout object, whose properties are defined in iostream.h represents
that stream.
• The insertion operator << also called the ‘put to’ operator directs the
information on its right to the object on its left.
C++ Console I/O (Output)
• cout << “Hello World!”;
• printf(“Hello World!”);
• cout << iCount; /* int iCount */
• printf(“%d”, iCount);
• cout << 100.99;
• printf(“%f”, 100.99);
• cout << “\n”, or cout << ‘\n’, or cout << endl
• printf(“\n”)
• In general, cout << expression;

11
Cascading Of I/O Operator:
• cout<<”sum=”<<sum<<”\n”;
• cout<<”sum=”<<sum<<”\n”<<”average=”<<average<<”\n”;
• cin>>number1>>number2;
Two Versions of C++
• A traditional-style C++ program -
#include <iostream.h>

int main()
{
/* program code */
return 0;
}
Two Versions of C++ (cont.)
• A modern-style C++ program that uses the new-style headers and a
namespace -
#include <iostream>
using namespace std;

int main()
{
/* program code */
return 0;
}
Namespaces
• A namespace is a declarative region.

• It localizes the names of identifiers to avoid name collisions.

• The contents of new-style headers are placed in the std


namespace.

• A newly created class, function or global variable can put in an


existing namespace, a new namespace, or it may not be
associated with any namespace.

15
STRUCTURE OF C++ PROGRAM

• Include files
• Class declaration
• Class functions, definition
• Main function program
Example :-
# include<iostream.h> void person::display()
class person {
{ cout<<”\n name:”<<name
char name[30]; cout<<”\n age:”<<age;
int age; }
public:
void getdata(); int main( )
void display();
{
};
person p;
void person :: getdata ()
p.getdata();
{
p.display();
cout<<”enter name”;
return(0);
cin>>name;
}
cout<<”enter age”;
cin>>age;
}
#include <iostream>
#include <iostream> using namespace std;
using namespace std; // namespace_1
// namespace_1 namespace space_1
namespace space_1 {
{ void func()
void func() {
{ cout << "Inside space_1" << endl;
cout << "Inside space_1" << endl; }
} }
}
// namespace_2
// namespace_2 namespace space_2
namespace space_2 {
{ void func()
void func() {
{ cout << "Inside space_2" << endl;
cout << "Inside space_2" << endl; }
} }
} using namespace space_1::space_2;
using namespace space_1; int main ()
int main () {
{ // This calls function from space_2.
// This calls function from space_1. func();
func();
return 0; return 0;
} }
TOKENS
The smallest individual units in program are known as tokens. C++ has the
following tokens.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
Keywords
• The keywords implement specific C++ language feature.

• They are explicitly reserved identifiers and can’t be used as names for the
program variables or other user defined program elements.

• C++ KEYWORDS are mentioned on next slide.


Identifiers
• Identifiers refers to the name of variable , functions, array, class etc.
created by programmer.
• Each language has its own rule for naming the identifiers.
• The following rules are common for both C and C++.
1. Only alphabetic chars, digits and under score are permitted.
2. The name can’t start with a digit.
3. Upper case and lower case letters are distinct.
4. A declared keyword can’t be used as a variable name.
In ANSI C the maximum length of a variable is 32 chars but in c++ there is
no bar.
Constants
• In both C and C++, any value declared as const can’t be modified by the
program in any way.
• In C++, we can use const in a constant expression.
• You must initialize a constant when you create it, and you can not assign
new value later, after constant is initialized.
• Defining constant using #define:
∙ #define is a preprocessor directive that declares
symbolic constant.
∙ Example syntax:
• #define PI 3.14
∙ Every time the preprocessor sees the word PI, it puts 3.14 in the text.
Example:
#include<iostream>
using namespace std;
#define PI 3.14;
int main()
{
int r,area;
cout<<”Enter Radius:”;
cin>>r;
area=PI*r*r;
cout<<”Area of Circle = ”<<area;
return 0;
}
Output:
Enter Radius :5
Area of Circle = 78.5
Defining constant using const keyword:

•‘const’ keyword is used to declare constant variable of any type.

• Syntax: const DataType Variable_Name=value;

Ex: const int a=2;

• Now ‘a’ is a integer type constant.


Operators: An operator is a symbol that tells the compiler to
perform certain mathematical or logical operation.

1.Arithmetical Operator 6. Conditional Operator


2.Relational Operator 7. Bitwise Operator
3.Logical Operator 8. Special Operator
4.Assignment operator 9. Extraction Operator
5.Increment and Decrement
Operators 10. Insertion Operator
11. Scope Resolution Operator
Arithmetic operators are used for mathematical
calculation. C++ supports following arithmetic operators.
• Relational operators are used to compare two numbers and taking
decisions based on their relation. Relational expressions are used in
decision statements such as if, for, while, etc…
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Logical operators are used to test more than one condition and make
decisions.

&& logical AND (Both non zero then true, either is


zero then false)

|| logical OR (Both zero then false, either is non


zero then true)

! logical NOT (non zero then false, zero then true)


Assignment operators are used to assign the result of an expression to a
variable. C++ also supports shorthand assignment operators which simplify
operation with assignment.
Increment and Decrement Operators
Conditional Operator
A ternary operator is known as Conditional Operator.
exp1?exp2:exp3
if exp1 is true then execute exp2 otherwise exp3
Ex: x = (a>b)?a:b; which is same as
if(a>b)
x=a;
else
x=b;
Bitwise Operators
• Bitwise operators are used to perform operation bit by bit.
Bitwise operators may not be applied to float or double.
Special Operators
• Extraction operator (>>)
Extraction operator (>>) is used with cin to input data from keyboard.
• Insertion operator (<<)
Insertion operator (<<) is used with cout to output data from keyboard.
• Scope resolution operator (::)
Scope resolution operator (::) is used to define the already declared
member functions of the class.
Memory Management Operators
• For dynamic memory management, C++ provides two unary operator
‘new’ and ‘delete’.
• An object can be created by using new, and destroy by using delete, as
and when required.
• Dynamic allocation of memory using new
• Syntax of new :
• pointer_variable = new data_type;
• Here pointer_variable is a pointer of any data type.
• The new operator allocates sufficient memory to hold a data object.
• The pointer_variable holds the address of the memory space allocated.
• For example:
• p=new int;
• q=new float;
• Type of ‘p’ is integer and type of ‘q’ is float.
• We can combine declaration and initialization.
• int *p=new int; float *q=new float;
• We can dynamic allocate space for array, structure and classes by new.
• int *p=new int[10];
• Allocates a memory space for an array of size 10.
• p[0] will refer location of p[1] and p[1] will refer location of [2] and so on.
• Release memory using delete
• When a data object is no longer needed, it is destroyed to release the
memory space for reuse.
• Syntax of delete: delete pointer_variable;
• The pointer_variable is the pointer that points to a data object created with
new.
• For example:
• delete p;
• delete q;
• To free a dynamically allocated array
• delete[size]pointer_variable;
• delete [10]p; OR delete [ ]p;
Basic Data types in C++
Enumerated Datatype
• An enumerated data type is another user defined type which provides a
way for attaching names to number, these by increasing comprehensibility
of the code.
• The enum keyword automatically enumerates a list of words by assigning
them values 0,1,2 and so on.
• This facility provides an alternative means for creating symbolic.
45
46
47
Control Structures
• Like c,c++, supports all the basic control structures and
implements them various control statements.
• The if statement:
The if statement is implemented in two forms:
1. simple if statement
2. if… else statement
1. Simple if statement:
if (condition)
{
Action;
}
2. If.. else statement
If (condition)
Statment1;
Else
Statement2 ;
Switch Statement
This is a multiple-branching statement where, based on a condition, the
control is transferred to one of the many possible points.
Switch(expr)
{
case 1: action1;
break;
case 2: action2;
break;
..
..
default: message
}
The while statement:
Syn:
While(condition)
{
Statements ;
}
The for loop:
for(expression1;expression2;expression3)
{
Statements;
Statements;
}
The do-while statement:
Syn:
do
{
Stements
} while(condition);
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’.
1. Done by the compiler on its own, without any external trigger from the
user.
2. 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.
3. All the data types of the variables are upgraded to the data type of the
variable with largest data type.
Implicit type conversion hierarchy
// 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
cout<< "y = " << y << endl
cout<< "z = " << z << endl;
return 0;
}
Output
x = 107
y=a
z = 108
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.
• Syntax:
• (type) expression
• where type indicates the data type to which the final result is
converted.
// 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
Reference variable
• A reference variable is an alias, that is, another name for an already
existing variable.
• Once a reference is initialized with a variable, either the variable name or
the reference name may be used to refer to the variable.
#include <iostream>
using namespace std;
int main () {
// declare simple variables
int i;
double d;
// declare reference variables
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
} Output
• Value of i : 5
• Value of i reference : 5
• Value of d : 11.7
• Value of d reference : 11.7
Thank you

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