• No results found

C++ Tutorials imp.ppt

N/A
N/A
Protected

Academic year: 2020

Share "C++ Tutorials imp.ppt"

Copied!
82
0
0

Loading.... (view fulltext now)

Full text

(1)

C++ TUTORIALS

(2)

What is C++?

C++ is an object oriented programming language.

C++ is an extension of C with a major addition of the

class construct feature.

C++ is superset of C.

Features like classes, inheritance, function overloading,

and operator overloading make C++ a truly object-oriented language.

OO features in C++ allow programmers to build large

(3)

What is C++ (II)

C++

Improves on many of C's featuresHas object-oriented capabilities

Increases software quality and reusability

Developed by Bjarne Stroustrup at Bell Labs

Called "C with classes“ (1979)

C++ (increment operator) (1983) - enhanced version of C

Superset of C

Can use a C++ compiler to compile C programsGradually evolve the C programs to C++

• ANSI C++

Final version at http://www.ansi.org/

(4)

Hello World!

/* Simple hello world program*/

# include <iostream>// This is include directive

using namespace std;

int main() {

cout << “Hello World!”; //C++ statement

(5)

Tokens

(6)

Tokens

Keywords

(7)

Keywords

Some words are reserved for implementing the specific C++

language features.

asm, auto, bool, break, case, catch, char,

class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true,

try, typedef, typeid, typename, union,

(8)

Tokens

(9)

Identifiers

Identifiers refer to the names of variables, functions,

arrays, classes , etc. created by the programmer.

Rules for creating it.

Only alphabet characters, digits and underscore are permitted.The name cannot start with digit.

Uppercase and lowercase letters are distinct.

(10)
(11)

Size and range of C++ basic data types

Type Bytes Range

char 1 -128 to 127

signed: -128 to 127 unsigned: 0 to 255

short int 2 -31768 to 32767

signed: -32768 to 32767 unsigned: 0 to 65535

int 2 -32768 to 32767

signed: -31768 to 32767 unsigned: 0 to 65535

long int 4 -2147483648 to 2147483647

signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

(12)

User-Defined Data Types

Structures and Classes

Basis for OOP.

Classes enable to combine data and procedures.

Enumerated Data Type

It provides a way to attaching names to the numbersIncrease comprehensibility of the code.

Alternative mean for creating symbolic constants

Enumerates a list of words by assigning them values 0,1,2 and so on.

(13)

Derived Data Types

Arrays

Values of similar type stored in continuous memory locations.

int a[10]; char string[3]=“xyz”;

Functions

Set of statements to perform specific tasks

Pointers

Special variables to store the memory location of other variables.Used in referencing memory.

(14)

Tokens

KeywordsIdentifiers

Constants

(15)

Constants (literal)

Refer to fixed values that do not change in thw execution

of the program.

123 //decimal integer

12.34 //floating point integer037 //octal integer

0x2 //Hexa decimal“C++” //string constant

‘A’ //character constant

(16)

Constants(Symbolic)

Using the qualifier const

const float pi = 3.14;

Using enum

enum{x,y,z};

enum{x=200,y=300,z=400};

(17)

Tokens

KeywordsIdentifiersConstants

Strings

(18)

Strings

Variables that can store non-numerical values that are

longer than one single character are known as strings.

The C++ language library provides support for strings

through the standard string class.

// my first string

#include <iostream> #include <string>

using namespace std; int main ()

{

Char mystring[ ] = "This is a string"; cout << mystring;

(19)

Tokens

KeywordsIdentifiersConstantsStrings

(20)
(21)

Expressions and Their Types

(22)

Control Structures

The if statement

Simple if statement if…..else statement

(23)

Control Structures

The switch statement

(24)
(25)

Control Structure

The do-while statement

do {

statement1; }

(26)

Control Structures

The while statement

while(condition) {

statement1; }

(27)

Control Structures

The for statement

for (intialization;condition;increment) {

statement1; }

(28)

Functions

A piece of code that perform specific task.Introduces modularity in the code.

Reduces the size of program.

C++ has added many new features to the functions to

make them more reliable and flexible.

(29)

Functions

Function declaration

return-type function-name (argument-list);void show();

float volume(int x,float y,float z);

Function definition

return-type function-name(argument-list) {

statement1; statement2; }

Function call

(30)

Functions

The main function

Returns a value of type int to the operating system.

int main() {

……… ………

(31)

Functions

Parameter Passing

Call by value

Copy of data passed to function

Changes to copy do not change originalCall by reference

Function can directly access data • Changes affect original

Reference variable Pointers

void swap (int &a, int &b) {

int t=a; a=b; b=t; }

(32)

Functions

Reference parameter alias for argumentUse &

void change(int &variable) {

variable += 3; }

• Adds 3 to the original variable input

int y = &x

Changing y changes x as well

(33)

Functions References

Dangling references

Make sure to assign references to variables

If a function returns a reference to a variable, make sure the

variable is static

Otherwise, it is automatic and destroyed after function ends

Multiple references

Like pointers, each reference needs an &

(34)

outline

1. Function prototypes

1.1 Initialize variables

2. Print x

2.1 Call function and print x

2.2 Print z

2.3 Call function and print z 

3. Function Definition

1 // Fig. 15.5: fig15_05.cpp

2 // Comparing call-by-value and call-by-reference 3 // with references.

4 #include <iostream>

5

6 using std::cout;

7 using std::endl;

8

9 int squareByValue( int );

10 void squareByReference( int & );

11

12 int main()

13 {

14 int x = 2, z = 4;

15

16 cout << "x = " << x << " before squareByValue\n"

17 << "Value returned by squareByValue: "

18 << squareByValue( x ) << endl

19 << "x = " << x << " after squareByValue\n" << endl;

20

21 cout << "z = " << z << " before squareByReference" << endl;

22 squareByReference( z );

23 cout << "z = " << z << " after squareByReference" << endl;

24

25 return 0;

26 }

27

28 int squareByValue( int a )

29 {

(35)

3.1 Function Definition

Program Output

x = 2 before squareByValue

Value returned by squareByValue: 4 x = 2 after squareByValue

z = 4 before squareByReference z = 16 after squareByReference

32

33 void squareByReference( int &cRef )

34 {

35 cRef *= cRef; // caller's argument modified

(36)

Default Arguments and Empty Parameter

Lists

• If function parameter omitted, gets default value

– Can be constants, global variables, or function calls

– If not enough parameters specified, rightmost go to their defaults

• Set defaults in function prototype

(37)

1. Function prototype (notice defaults)

2. main

2.1 Function calls (use default arguments)

3. Function definition

1 // Fig. 15.8: fig15_08.cpp

2 // Using default arguments

3 #include <iostream>

4

5 using std::cout;

6 using std::endl;

7

8 int boxVolume( int length = 1, int width = 1, int height = 1 );

9

10 int main()

11 {

12 cout << "The default box volume is: " << boxVolume()

13 << "\n\nThe volume of a box with length 10,\n"

14 << "width 1 and height 1 is: " << boxVolume( 10 )

15 << "\n\nThe volume of a box with length 10,\n"

16 << "width 5 and height 1 is: " << boxVolume( 10, 5 )

17 << "\n\nThe volume of a box with length 10,\n"

18 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )

19 << endl;

20

21 return 0;

22 }

23

24 // Calculate the volume of a box

25 int boxVolume( int length, int width, int height )

26 {

27 return length * width * height;

(38)

Program Output

The default box volume is: 1

The volume of a box with length 10, width 1 and height 1 is: 10

The volume of a box with length 10, width 5 and height 1 is: 50

(39)

Function Overloading

C++ allows to use the same function name to create functions that perform a variety of different tasks. ORFunctions with same name and different parameters

Overloaded functions should perform similar tasks

This is know as function polymorphism in OOP. • Function to square ints and function to square floats

int square( int x) {return x * x;}

float square(float x) { return x * x; }

• Program chooses function by signature

• Signature determined by function name and parameter types • Type safe linkage - ensures proper overloaded function called

int add (int a, int b); //prototype 1

int add (int a, int b, int c); //prototype 2 double add (double x, double y);//prototype 3 double add (int p, double q);//prototype 4 double add (double p, int q); //prototype 5

(40)

1. Define overloaded function

2. Function calls

Program Output

1 // Fig. 15.10: fig15_10.cpp 2 // Using overloaded functions 3 #include <iostream>

4

5 using std::cout;

6 using std::endl;

7

8 int square( int x ) { return x * x; }

9

10 double square( double y ) { return y * y; }

11

12 int main()

13 {

14 cout << "The square of integer 7 is " << square( 7 )

15 << "\nThe square of double 7.5 is " << square( 7.5 )

16 << endl;

17

18 return 0;

19 }

The square of integer 7 is 49

(41)

Inline Functions

Function calls

Cause execution-time overhead

Qualifier inline before function return type "advises" a function

to be inlined

Puts copy of function's code in place of function call

Speeds up performance but increases file sizeCompiler can ignore the inline qualifier

Ignores all but the smallest functions

(42)

Inline fun example

#include<iostream.h>class clsnam

{ public: int num;

inline void fun(int & a,int & b) {

cout<<"a="<< a; }};

(43)

Friend Function?

What is a Friend Function?

A friend function is used for accessing the non-public members of a

class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class.

How to define and use Friend Function in C++:

The friend function is written as any other normal function, except the

(44)

Friend Fun Example

#include<iostream.h>class clsnam

{

friend void fun(int a,int b); public: int num;

};

void fun(int a,int b) {

cout<<"a="<< a; }

void main(){

(45)

Structures

Structures Revisited

Makes convenient to handle a group of logically related data

items.

struct student //declaration {

char name[20]; int roll_number; float total_marks; };

struct student A;// C declaration student A; //C++ declaration A.roll_number=999;

A.total_marks=595.5;

(46)

Structures

Limitations

C doesn’t allow it to be treated like built-in data types.

struct complex{float x; float y;}; struct complex c1,c2,c3;

c3=c1+c2;//Illegal in C

(47)

Structures in C++

Can hold variables and functions as members.

Can also declare some of its members as ‘private’.

C++ introduces another user-defined type known as

(48)

Classes and Objects

Class is a way to bind the data and procedures that

operates on data.

Class declaration:

class class_name {

private:

variable declarations;//class function declarations;//members public:

(49)

Classes and Objects

Class members that have been declared as private can

be accessed only from within the class.

Public class members can be accessed from outside the

class also.

Supports data-hiding and data encapsulation features of

(50)

Classes and Objects

Objects are run time instance of a class.

Class is a representation of the object, and Object is the

actual run time entity which holds data and function that has been defined in the class.

Object declaration:

class_name obj1;

class_name obj2,obj3; class class_name

(51)

Classes and Objects

Accessing class members

Object-name.function-name(actual-arguments);

obj1.setdata(100,34.4);

Defining Member Functions

Outside the class definition.

return-type class-name::function-name (argument declaration)

{

Function body; }

Inside the class definition.

(52)
(53)

Classes and Objects

Object as arrays

class employee {

char name [30]; float age;

public:

void getdata(void); void putdata(void); };

employee manager[3];//array of manager employee worker[75];//array of worker

(54)

Friendly Function

Friend function are used in the situation where two

classes want to share a common function.

Scientist and manager classes want to share the function

incometax().

C++ allows the common function to be made friendly with

(55)

Friend Function Characteristics

It is not in the scope of the class, hence it cannot be

called using the object of any class. It can be invoked normally.

It cannot access member names directly, but with the help

of an object. Eg obj1.x

It can be declare either in the public or the private part of

a class without affecting its meaning.

(56)

Program: Friend Function

Friend function sample: #include <iostream.h>

//Declaration of the function to be made as friend for the C++ Tutorial sample int AddToFriend(int x);

class CPP_Tutorial {

int private_data;

friend int AddToFriend(int x); public:

CPP_Tutorial() {

private_data = 5; }

};

int AddToFriend(int x) {

CPP_Tutorial var1;

return var1.private_data + x; }

int main() {

cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<<endl; } The output of the above C++ Tutorial sample will be

(57)

Constructors and Destructors

In order to behave like built-in data types, the derived-data

types such as ‘objects’ should automatically initialize when created and destroys when goes out of scope.

For this reason C++ introduces a special member

(58)

Constructors

Name is same as that of class.

Invoked when ever an object of its associated class is

created.

class integer {

int m,n; public:

integer(void); ….

…. };

(59)

Constructors Characteristics

Declared in the public section.

Invoked automatically when the objects are created.Do not have return type.

Cannot be inherited. Though a derived class can call the

base class constructor.

Can have default arguments.Cannot be virtual.

We cannot refer to their addresses.

An object with a constructor (or destructor) cannot be

used as a member of a union.

They make ‘implicit calls’ to the operators ‘new’ and

(60)

Constructors

Parameterized Constructors

class integer {

int m,n; public:

integer(int x, int y); ….

…. };

integer :: integer(int x,int y){ m=x;n=y;} integer num1 = integer(0,100);//explicit call

(61)

Constructors

Multiple Constructors

class integer {

int m,n; public:

integer(void);

integer(int x, int y); ….

…. };

integer :: integer(void){ m=0;n=0;}

(62)

Constructors

Dynamic initialization of Objects

cin>> real>>imag;

Obj1=complex(real,imag);

Copy Constructor.

class integer {

int m,n; public:

integer(integer &i){m=i.m;n=i.n;}; ….

};

(63)

Destructors

Is used to destroy the objects that have been created.

~complex(){}

(64)

Operator Overloading

C++ tries to make the user-defined data types behave in

much the same way as the built-in data types.

In built-in data types we have:

c=a+b//a,b and c are of type ‘int’.

We can also have in C++:

object1=object2+object3;

C++ has the ability to provide the operators with a special

meaning for a data type. This mechanism is known as

(65)

Defining Operator Overloading

return-type class-name::operator op (arglist)

Operator functions must be either member functions or

friend functions.

vector operator+(vector);

vector operator-();

friend vector operator+(vector,vector);

friend vector operator-(vector);

int operator==(vector);

(66)
(67)
(68)

An Example: Operator Overloading

with Friend Function

friend void operator-(space &s);

void operator-(space &s) {

(69)

Overloading Binary Operators

a, b and c are objects of class ‘complex’

c=a.sum(b);//functional notation, function

‘sum’ is member function.

c=sum(a,b);//functional notation, function

‘sum’ is friend function.

c=a+b; // arithmetic notation, can be

(70)

Overloading Binary Operators

Using member functions

complex complex::operator+(complex c) {

(71)

Overloading Binary Operators

Using friend function.

friend complex operator+(complex, complex); //declaration

(72)

Inheritance

C++ strongly support the concept of reusability.C++ classes can be reused in several ways.

Creating new classes by reusing the properties of

existing once.

The reuse of a class that has already been tested,

debugged and used many times can save us the effort of developing and testing the same again.

Mechanism is Inheritance.

(73)
(74)

Defining Derived Class

class derived-class-name : visibility-mode base-class-name {………};

Visibility mode is optional.(by default: private)

Visibility mode specifies whether the features of the base

(75)
(76)
(77)
(78)

An Example: Single Inheritance,

Private Derivation

d.get_ab(); d.get_a(); d.show();

Will not work.

void mul() void display()

{ {

get_ab(); show_a();

c=b*get_a(); cout<<“b=“<<b<<“\n”

} <<“c=”<<“\n\n”;

(79)

Inheritance: Private, Protected and

Public

Inside the class. class alpha {

private://optional

…………//visible inside this class only

protected://visible inside this class …………//and its immediate derived class

public://visible to all …………

(80)
(81)

Inheritance: Different types

Multilevel Inheritance

class A{…};

Class B : public A{…}; Class C : public B{…};

Multiple Inheritance

(82)

References

Related documents

From the above observations 96% strongly agree that training programs conducted at Ongc helped the From the above observations 96% strongly agree that training

• Write operator* for Complex numbers as an ordinary non-member function instead of as a member function of the Complex class.. Show the additions to Complex.h

1) Classes can have private member functions. 2) Classes can have both public and private data members. 3) By default, members of classes are private. 5) Aggregate

Many classes have member functions that provide access to data in private containers (e.g. vectors); they are usally accompanied by a member function that returns the number of

 private class members can be accessed only by the class member functions (and friend functions), not by client code... Aggregate

Figure 44: Contour plot of horizontal instantaneous velocity for Libeccio wind simulation, at three different horizontal planes: (A) sea surface, (B) three meters under sea surface,

 In this example, class Rectangle is a friend of class Square allowing Rectangle's member functions to access private and protected members of Square. More

protected: only member functions of the same class or of derived classes can access it: other classes or global functions can’t public: every function can access it. class MyClass