3. #
LECTURE PLAN
1. Introduction to Visual C++ / Visual Studio. Net
2. Structures & Classes.
3. Function Overloading & Default Arguments.
4. Friend Function & Friend Class
5. Constructor & Destructor
6. Operator Overloading.
7. C++ Standard String Class. MID TERM EXAM
8. Static Variable & Functions.
9. Inheritance.
10. Virtual Function & Templates (Polymorphism).
11. File Streams.
12. Exception Handling.
13. Project. FINAL EXAM
4. #
Introduction to Visual Studio .Net
• Visual Studio .NET is a complete set of development
tools for building Web applications, XML Web
services, Desktop applications, and Mobile
applications.
• Visual Basic .NET, Visual C++ .NET, Visual C# .NET,
and Visual J# .NET all use the same integrated
development environment (IDE), which allows them
to share tools and facilitates in the creation of
mixed-language solutions.
5. #
Creating New Project :
• File – New – Project
– Project Types: Visual C++ Project
– Templates: Empty Project (.NET)
Window Console 32 Application (Visual C++)
– Name: Project Name
– Location: Location to Save
File – New – fileFile – New – file
Categories:Categories: Visual C++Visual C++
Templates:Templates: C++ file (.CPP)C++ file (.CPP)
Write Code & Save it at Appropriate location.Write Code & Save it at Appropriate location.
File – Move Source1.CPP into Project -File – Move Source1.CPP into Project -
Select Appropriate Project Name.Select Appropriate Project Name.
6. #
Structure
• A structure is a collection of simple variables of
different data types.
• The data in a structure is called “members of the
structure”.
• The keyword “struct” introduces the structure
definition.
EXAMPLE :
struct part
{
int modelnumber;
float cost;
};
7. #
Structure (Contd.)
• Next to struct is structure name (or Tag).
• The declaration of the structure members are enclosed in
braces.
• Each structure definition must end with a semicolon ;
• Two different structures may contain members of the same
name.
• Members of the structure can be accessed by the DOT
OPERATOR. (e.g. part.cost)
• Data members cannot be initialized in structure except “const
static integral data members”.
8. #
struct dist
{
int feet;
float inches;
};
void main( )
{
dist d1;
cin>>d1.feet;
cin>>d1.inches;
dist d2 = { 30,40 };
cout<<d1.feet<<endl;
cout<<d2.feet<<endl;
cout<<d1.inches<<endl;
cout<<d2.inches<<endl;
int f = d1.feet + d2.feet;
float i = d1.inches +
d2.inches;
i /=12;
f += i;
cout<<f<<“ Feet ”;
getch( );
}
10. #
Passing Objects to a function:
Similar to passing variables to functions , one
may pass the objects of a structure to a
function.
Vice Versa, objects can also be returned from a
function.
11. #
Q1.
Create a employee structure. The member
data should comprise one integer for
storing the employee id, one long integer
for storing his salary, and a floating
number for storing the employee’s
pension. Create two functions, one for
entering this data and other to display it.
Write a main( ) that allows the user to call
these functions.
12. #
Q2: Calculate Areas.
Press
1 To calculate Area of Circle ( RΠ 2
)
2 To calculate Area of Square (L2
)
3 To calculate Area of Rectangle (L*W)
4 To calculate Area of Triangle (B*H*0.5)
13. #
Q3:
Write a C++ structure function which converts
a sum of money given as an integer number of
pence into a floating point value representing
the equivalent number of pounds. For
example 365 pence would be 3.65 pounds.
15. #
Rules for using Default Arguments:
• Only trailing arguments may be defaulted. That
is, one cannot have a default argument
followed by a non-default argument.
• Once one start using default arguments in a
particular function call, all the subsequent
arguments in that function’s argument list must
be defaulted.
16. #
Example: void repchar (char ch=‘x’, int val = 5) ;
void main ( )
{
repchar( );
repchar( ‘w’ );
repchar( ‘t’ , 20 );
repchar( 20 );
getch( );
}
void repchar (char ch, int n)
{
for (int j=0 ; j<n ; j++)
cout<<ch;
cout<<endl;
}
17. #
Class Assignment (Def. Arg.)
Calculation of Area of
SQUARE, RECTANGLE and TRIANGLE.
func1 ( ): Comparing condition & calling
of function mydef( )
mydef( ): multiply all arguments and print
result.
main( ): calling func1.
18. #
Function Overloading
• Function overloading is the practice of declaring the functions
of same name but with different signatures.
• The same function name can be used with different number
of parameters and parameters of different type.
• Typically, function overloading is used wherever a different
type of data is to be dealt with. For example this can be used
for a function which converts Fahrenheit to Celsius and vice
versa. One of the functions can deal with the integer data,
other can deal float for precision etc.,
19. #
• Overloading of functions with different return
type is not allowed in C++.
• When an overloaded function is called, the
correct function is selected by comparing their
argument list.
20. #
Examples:
• void func ( );
• void func (int a);
• void func (float a, int b);
• void func (float a, float b);
• void func (int a, char b);
• int func (float a, float b); // illegal function
22. #
CLASSESCLASSES::Classes are fundamental components of a C++ program (Like Structure).
A class is an expanded concept of a structure.
A class is a mechanism for creating user-defined data types.
Classes can contain member functions that operate on their data members.
Classes are generally declared using the keyword class, with the following format:
Access Specifiers
24. #
Class is similar to the C language structure data type. In C, a
structure is composed of a set of data members. In C++, a class
type is like a C structure, except that a class is composed of a set
of data members and a set of operations (functions) that can be
performed on the class.
Difference b/w Class and C language Structure:
1:By default, the members of structures are public while that for
class is private
2:Structures doesn't provide something like data hiding which is
provided by the classes
3:Structures in C language contains only data while class bind
both data and member functions
25. #
Difference b/w Class & C++ language Structure:
The keywords struct and class are almost interchangeable in
C++. You can declare a struct that has member functions,
constructors, destructor, base classes and so on as if it were
a class. Likewise, it's possible to create a class that has only
public data members. The only difference between a struct
and a class is in the default access. By default, all the
members of a struct are public whereas in a class, all the
members are private.
Main Difference: “Access Specifier”
26. #
Access Specifiers:
public: can be used anywhere without the
access restrictions defined by private or
protected.
private: can be used only by the members and
friends of class A.
protected: can be used only by the members
and friends of class A, and the members and
friends of classes derived from class A.
A friend of a class X is a function or class
that is not a member of X, but is granted the
same access to X as the members of X.
27. #
Constructor:
• A constructor is a member function with the same
name as its class.
e.g. Part( arguments ){}
• Constructor do not return any value. Neither void
nor any return type.
• Constructors are used for initialization of the
variables.
• Constructors are called at a point an object is
created.
• Default Constructor takes no arguments.
28. #
Destructor:
• A destructor is a member function with the
same name as its class prefixed by a ~ (tilde).
e.g. ~Part(){}
• Destructors are usually used to de-allocate
memory and do other cleanup for a class
object and its class members when the object
is destroyed.
• A destructor takes no arguments and has no
return type.
29. #
Example 1: class smallobj
{
private:
int somedata;
public:
void setdata(int d)
{
somedata = d ;
}
void showdata( )
{
cout<<”Data is ” <<somedata<<endl;
}
};
void main ( )
{
smallobj s1,s2;
s1.setdata(100);
s2.setdata(150);
s1.showdata( );
s2.showdata( );
}
In C++, the term
object refers to
an instance of a
class.
30. #
USING CLASS AND MEMBER FUNCTIONS
Q1. Write a program which works as a Money Exchanger.
– User Input: Dollars/Rupees
Rates of Money Exchanger are as follows:
The buying price of dollar is 60.04 Rs.
The selling price of dollar is 60.50 Rs.
Q2. Write a program using two classes, one for circle and the other for
sphere. Use member functions to calculate the area of both objects.
31. #
Friend Function:
– A friend function is a function that is not a
member of a class but has access to the class's
private and protected members.
– Friend functions are not considered class
members; they are normal external functions
that are given special access privileges.
32. #
class car
{
private:
int speed;
int model;
public:
void input( )
{
cout<<"Enter the model”;
cin>>model;
cout<<"Enter the speed”;
cin>>speed;
}
void print( )
{
cout<<speed;
cout<<model;
}
friend car display (car);
};
car display (car x)
{
cout<<"nThe model of the car is :
"<<x.model;
cout<<"nThe speed of the car is :
"<<x.speed;
return x;
}
void main( )
{
car mine;
mine.input( );
mine=display(mine);
mine.print( );
getch();
}
ExampleExample: Friend Function: Friend Function
33. #
Friend Function:
– A function can be declared as friend of more than
one class.
– Friend Function must be declared in each class.
34. #
class virus;
class bacteria
{
private:
int life;
public:
bacteria( )
{
life=1;
}
friend void check (bacteria,virus);
};
class virus
{
private:
int life;
public:
virus( )
{
life = 0;
}
friend void check
(bacteria,virus);
};
void check (bacteria b ,virus v)
{
if (b.life= =1 || v.life= =1)
cout<<"nSomething is alive";
if (b.life = = 1)
cout<<"nA bacteria is alive.";
ExampleExample: Friend Function: Friend Function
35. #
void check (bacteria b ,virus v)
{
if (b.life= =1 || v.life= =1)
cout<<"nSomething is alive";
if (b.life = = 1)
cout<<"nA bacteria is alive.";
if (v.life = = 1)
cout<<"nA virus is alive.";
}
void main( )
{
bacteria fever;
virus cholera;
check (fever, cholera);
getch ( );
}
ExampleExample: Friend Function: Friend Function
36. #
class Tutorial
{
int data;
friend int Add (int x);
public:
Tutorial ( )
{
data = 5;
}
};
int Add (int x)
{
Tutorial var1;
return var1.data + x;
}
void main( )
{
cout<<"Result"<<Add(4)<<endl;
getch();
}
ExampleExample: Friend Function: Friend Function
37. #
REMEMBER :
• The friend functions are not member of any class,
but they can be used to access private data of one or
more classes to which they are friend. No other
function can do that!
• Since they are not members of any class, one should
not call them using the dot operator.
• One should declare the friend function in both the
classes where you want it to be a friend
• A friend declaration can be placed into either private
or public section of a class. it does not make any
difference. (Standard: public)
38. #
Friend Class:
– A class can be a friend of another class, which
means, the friend class will have access to all the
private members of the other class.
39. #
class add
{
int x, y;
public:
add( )
{
x=y=4;
}
friend class support;
};
class support
{
public:
void sum (add ob)
{
cout<<"The sum of the two
members is : "<< (ob.x + ob.y);
}
};
void main( )
{
add ad;
support sup;
sup.sum(ad);
getch ( );
}
output:
The sum of the 2 members is: 8
Example:Example:
40. #
OPERATOR OVERLAODING
– C++ allows almost all operators to be overloaded. i.e. their meaning
can be redefined for different objects.
– One cannot introduce new operators. Only existing operators can be
overloaded. e.g. one cannot create the operator +*.
– The operator keyword declares a function specifying what operator-
symbol means when applied to instances of a class. This gives the
operator more than one meaning, or "overloads" it.
– The compiler distinguishes between the different meanings of an
operator by examining the types of its operands.
– Overloaded operators are implemented as functions
return_type operator operator_symbol ( parameter-list )
List of Redefinable and Nonredefinable Operators is available on :
http://msdn2.microsoft.com/en-us/library/5tk49fh2.aspx
46. #
OPERATOR OVERLAODING
– Operator overloading work only with user defined objects. (NOT with
basic data types).
– Operator functions can be global or member functions. (if global, often
are friend functions).
– Ability to redefine the operators can make your program more
readable and easy to understand.
– On other hand, it can also make your program more difficult and hard
to understand.
– THUS USE SIMILAR MEANINGS.
– Use overloaded operators only when usage is obvious. Otherwise, use
a function instead of overloaded operator, since function name can
state its own purpose.
47. #
1. Overload + operator , for addition purpose.
2.
• a. Write a program to calculate salary of a employee (before taxes
given the hours worked and the hourly rate. The program output
should look similar to: (USING *= OPERATOR OVERLOADING)
• b. Extend the program for calculating Monthly Salary of more than one
employee.
• c. Firm employs students who are exempted from taxes and others
who are not. Modify the program so that if an employee is not exempt,
10% will be deducted from Salary, otherwise "NO TAXES DEDUCTED"
will be displayed.
Class AssignmentsClass Assignments
48. #
Two program runs are shown below:
Enter hours worked by Employee 1: 45
Enter hourly rate: 10.00
Exempted: Y/N Y
Salary: $ 450.00
…………….
…………………..
Enter hours worked by Employee 2: 40
Enter hourly rate: 20.00
Exempted: Y/N N
Salary: $ 720.00
49. #
MEMORY ALLOCATION
What is memory allocation:
• The fixed amount of memory which is required by a
program to store the values of its variables and data
structures.
• In C++ there are two different types of memory
allocation that can be used to hold the content of
program variables.
– Static memory allocation
– Dynamic memory allocation
50. #
STATIC MEMORY ALLOCATION
• In C++, compiler allocate static memory for a
program.
• Static memory has fixed size and fixed location.
• The location or size of static memory do not change
during the lifetime of program.
• When a program begins to execute, there must be
some specific blocks of memory, set aside for its use.
• This memory block cannot be used by another
program.
Static Memory Allocation using Arrays
Static array of 10 integers: int myarray[10];
(This array is created at compilation time.)
51. #
EXAMPLE: (Static Memory Allocation)
void main( ) {
int myarray[ ] = {5,10,15};
void print(myarray, 3);
}
void print (int a[ ], int length)
{
for (int n=0; n<length; n++)
cout<<a[n]<<endl;
}
• The size of the array is fixed and cannot be changed at run time.
• In C++, we use normally static arrays. But the disadvantage with
the static arrays is that once we have declared the array of a
particular size, we cannot change its size when program is
running. So the solution for this problem is to use the dynamic
array allocation.
52. #
DYNAMIC MEMORY ALLOCATION
• In last program we had fixed size of memory
size for array element. But what will happen if
we need variable amount of memory, which
can only be determined during the execution
time.
• Then we require DYNAMIC MEMORY.
• In case of dynamic array, the size of an array
does not know by the compiler in advanced.
This dynamic memory is allocated by the
system at the runtime. To allocate memory
dynamically, we have to use pointers.
53. #
• The real power of pointers is seen when they are used
to point dynamically allocated variables.
• But the dynamic allocation does not mean that we can
create new variables names during execution time.
• It is necessary that compiler must know all the
variables identifiers at the compile time. For this
reason, creating dynamic memory involves two steps:
1. Create a statically allocated pointer. int * ptr;
2. Create dynamic space and store its address in pointer.
We use the name of pointer to refer to the dynamic memory.
So it is important to note here dynamic allocate memory
through a pointer.
54. #
• Static arrays are declared prior to execution time and are
reserved in stack memory, whereas dynamic memory are
created and released using the special C++ new and delete
operators respectively at execution time.
• In C++ to dynamically allocate memory, we use the new
operator. For Example:
new int;
new float;
• The new int is used for dynamically memory allocation for an
integer variable at runtime.
• Thus if we want to create an array of forty integers we will
write int * ptr = new int [40];
• Here ptr is an integer pointer and we are creating an array of
40 integer element.
55. #
Rule of new operator:
• new operator returns the address of the allocated
space, so we must capture this address space
pointer.
• so, in the integer array dynamic memory allocation,
we will declare an integer pointer to capture the
address space pointer which will be returned by the
new operator.
• Now if array size is changed from a constant value to
any variable we can take this value from the user at
runtime.
56. #
• As we know that we never need to worry about getting rid of
statically allocated memory.
• Static variables and static arrays are automatically handled by
the compiler which has already determined their scope and
their lifetime.
• But there is a problem in Dynamic Memory Allocation that this
memory is created on the free store. If we do not release this
memory this will become the memory leak.
• Anything we will create dynamically will be ignored by the
compiler. It is necessary to de allocate this allocated memory
for the reuse.
• For this purpose, in C++ an operator delete is used to de-
allocate the dynamic memory.
57. #
• To de-allocate dynamically allocate memory, apply the delete
operator to the pointer, and it will delete the dynamic
memory that the pointer is pointing to.
• It is important to note that this does not de-allocate the
pointer but the only free the dynamic memory. Syntax used
for de-allocation of an array is
delete [ ] pointer name;
• In case of objects, destructor are called.
• Dynamic array is nice as the size of the array can be
determined at runtime and then using size with the new
operator to allocate space.
58. #
class DynamicArray{class DynamicArray{
private:private:
int * array;int * array;
/*integer type pointer holds the address of/*integer type pointer holds the address of
the dynamic array which is created at thethe dynamic array which is created at the
runtime. */runtime. */
int size;int size;
/* integer type variable tells the total/* integer type variable tells the total
number of the elements of array. */number of the elements of array. */
public:public:
DynamicArray (int arraysize);DynamicArray (int arraysize);
//Constructor//Constructor
~DynamicArray( );~DynamicArray( );
//Destructor//Destructor
void ChangeSize (int arraysize);void ChangeSize (int arraysize);
//To change size of array//To change size of array
void PrintArray( );void PrintArray( );
//To print the elements of the array.//To print the elements of the array.
};};
DynamicArray :: DynamicArray (intDynamicArray :: DynamicArray (int
arraysize)arraysize)
size of array is size of array is
passed as parameterpassed as parameter
{{
array = new int [arraysize] ;array = new int [arraysize] ;
/*Dynamic array is created and the address/*Dynamic array is created and the address
of the dynamic array is stored in an integerof the dynamic array is stored in an integer
pointer “array.” */pointer “array.” */
for (int i=0 ; i<arraysize ; i++)for (int i=0 ; i<arraysize ; i++)
// initializing the elements.// initializing the elements.
array [ i ] = i ;array [ i ] = i ;
size = arraysize;size = arraysize;
}}
DynamicArray :: ~DynamicArray ( )DynamicArray :: ~DynamicArray ( )
// to delete the dynamic array.// to delete the dynamic array.
{{
delete [ ] array;delete [ ] array;
}}
ExampleExample::
59. #
void DynamicArray :: ChangeSize(intvoid DynamicArray :: ChangeSize(int
arraysize)arraysize)
{{
delete [ ] array;delete [ ] array;
//delete previously allocated Dynamic array.//delete previously allocated Dynamic array.
array = new int [arraysize];array = new int [arraysize];
// create new array.// create new array.
for(int i=0 ; i<arraysize ; i++)for(int i=0 ; i<arraysize ; i++)
// initialization.// initialization.
array [ i ] = i ;array [ i ] = i ;
size = arraysize;size = arraysize;
}}
void DynamicArray :: PrintArray( )void DynamicArray :: PrintArray( )
{{
for (int i=0 ; i<size ; i++)for (int i=0 ; i<size ; i++)
cout<< array [ i ] << ” t ”;cout<< array [ i ] << ” t ”;
cout<<endl;cout<<endl;
}}
void main( )void main( )
{{
DynamicArray a1(2), a2(5);DynamicArray a1(2), a2(5);
a1.PrintArray( );a1.PrintArray( );
a2.PrintArray( );a2.PrintArray( );
a1.ChangeSize(7);a1.ChangeSize(7);
a2.ChangeSize(10);a2.ChangeSize(10);
a1.PrintArray( );a1.PrintArray( );
a2.PrintArray( );a2.PrintArray( );
}}
ExampleExample: (Contd.): (Contd.)
60. #
#include<iostream.h>
#include<conio.h>
class square
{
private: int length, width, result;
public:
square (int a, int b) { length=a; width=b; }
void print ( )
{ cout<<"The area of square is : "<<result<<endl; }
friend void area (square &sqr1);
};
void area (square &sqr1)
{ sqr1.result = sqr1.length * sqr1.width; }
void main( )
{
square sqr1( 2,3 );
area(sqr1) ;
sqr1.print();
}
61. #
• It provides a number of string manipulation operations
such as copying, searching, replacing etc. “string” class
allows the use of overloaded operators (e.g. +, +=, = =).
DIFFERENT WAYS TO DEFINE OBJECT:
• string str;
• string str (“Man”);
• string str = “Man”;
• string str(8, ‘x’);
[string containing eight ‘x’ characters].
THE STANDARD C++ STRING CLASSTHE STANDARD C++ STRING CLASS
62. #
• The stream extraction operator (>>) is also overloaded to support
strings. The statement
string str;
cin >> str;
reads a string from the keyboard. Input is delimited by white-space
characters. When a delimiter is encountered, the input operation is
terminated.
• Function getline is also overloaded for strings. The statement
string str;
getline (cin,str);
reads a string from the keyboard. getline can read a line of text and
saves it into a string object.
63. #
STRING FUNCTIONS:
• getline (cin, str); getline(cin, str, delim);
Reads a string from keyboard
• str.length( ); / str.size( );
Returns the size/length of the string str.
• str.empty ( );
Informs if the string is empty or not. Returns true (1)
or false (0).
64. #
STRING FUNCTIONS (Contd.)
ASSIGNMENT AND CONCATENATION:
str1.assign (str2); (Alternative str1=str2;)
Assigns the value of str2 to str1
str [2] = ‘r’;
Assigns value ‘r’ to the 2nd index of string str.
str.at (4);
Returns character at 4th index of string str.
str.append (“bomb”); (Alternative str += “bomb”;)
Append string str and “bomb”.
str.append (str1, StartIndex, Length);
Appends string str1 with string str.
65. #
STRING FUNCTIONS (Contd.)
COMPARING STRINGS:
• str1.compare(str2);
Compares string str2 with string str1. Returns an integer value.
If both are equal returns 0. Returns a positive number if string str1 is greater, while
returns negative number if string str2 is greater than string str1.
(str1 == str2), (str1 < str2), (str1 > str2)
• str1.compare (StartIndex, Length, str2, StartIndex, Length);
Compares a part of string str1 with a part of string str2. Returns an integer value.
• str1.compare(StartIndex, LengthOfIndex, str2);
Compares a part of string str1 with string str2. Returns an integer value.
66. #
ASSIGNMENT:
• Define two strings str1, str2.
• Check if both strings are empty.
• Assign values “Amjad Khan” & “ studying at
University” to string str1 and str2 respectively.
• Check length of both strings.
• Print the character on index 2.
• Check if str1 is greater than str2 and vice versa.
• Append “ is” at the end of str1.
• Replace character ‘d’ with ‘q’.
• Append str1 with str2.
67. #
STRING FUNCTIONS (Contd.)
SUBSTRING:
• str1=str2.substr (StartIndex, LengthOfIndex);
Retrieves a substring of a string str2.
SWAPING STRING:
• str1.swap(str2);
Swaps the values of string str1 and str2.
68. #
STRING FUNCTIONS (Contd.)
FINDING STRINGS & CHARACTERS IN A STRING:
• str.find (“is”);
Returns the location (starting index) of the string “is” in a string str. (Forward Search)
• str.find (“is”, position+1);
Returns the location (starting index) of the string “is” in a string str. (Forward Search).
Function takes two arguments: The string to search and the index from where search must
start.
• str.rfind (“is”);
Returns the location (starting index) of the string “is” in a string str. (Backward Search)
• str.find_first_of(“abcd”);
Locates the first occurrence in the string str of any character in “abcd”.
• str.find_last_of(“abcd”);
Locates the last occurrence in the string str of any character in “abcd”.
69. #
STRING FUNCTIONS (Contd.)
REPLACING CHARACTERS IN A STRING:
• str.replace (index, 3, “The”);
Used to replace the character in a string. Function takes three
arguments: the location in the string at which replacement should
begin, the number of characters to replace and the replacement
string.
• str.erase (6);
Used to erase everything from (and including) the character in
position 6 to the end of string str.
• str.erase(5 , 8);
Used to erase from (and including) the character in position 5 till the
next 7 characters. (Index 5-12)
71. #
Static Local Variables
Static local variables are used when it is necessary for a function
to remember a value of a variable.
A static local variable has the visibility of an automatic local
variable.
Its life time is same as global variable except that it does not
come into existence until the first call to the function containing
it.
The declaration of a static variable begins with keyword “static”.
72. #
# include <iostream.h># include <iostream.h>
# include <conio.h># include <conio.h>
float getavg (float);float getavg (float);
void main( )void main( )
{{
clrscr();clrscr();
float data=1, avg;float data=1, avg;
while (data!=0)while (data!=0)
{{
cout<<“nEnter a number”;cout<<“nEnter a number”;
cin>>data;cin>>data;
avg = getavg(data);avg = getavg(data);
cout<<“nNew Avg is”<<avg;cout<<“nNew Avg is”<<avg;
getch( );getch( );
}}
}}
float getavg (float newdata)float getavg (float newdata)
{{
static float total = 0;static float total = 0;
static int count = 0;static int count = 0;
count++;count++;
total+=newdata;total+=newdata;
return (total/count);return (total/count);
}}
ExampleExample::
73. #
Static Variables
An object of a class has its own copy of all the members of the
class.
Static variables are used when only copy of a variable should be
shared by all objects of a class.
The declaration of a static member begins with keyword “static”.
Static members can be declared public, private or protected.
It is visible only within a class but its lifetime is the entire
program.
74. #
# include <iostream.h># include <iostream.h>
# include <conio.h># include <conio.h>
class fooclass foo {{
private:private:
static int count;static int count;
public:public:
foo ( )foo ( )
{ count++; }{ count++; }
int getcount( )int getcount( )
{ return count; }{ return count; }
};};
int foo::count = 0;int foo::count = 0;
void main( )void main( )
{{
clrscr();clrscr();
foo f1, f2, f3;foo f1, f2, f3;
cout<<“count:”<<f1.getcount();cout<<“count:”<<f1.getcount();
cout<<“count:”<<f2.getcount();cout<<“count:”<<f2.getcount();
cout<<“count:”<<f3.getcount();cout<<“count:”<<f3.getcount();
getch( );getch( );
}}
Static data members require twoStatic data members require two
separate statements. The variable’sseparate statements. The variable’s
declaration appears in the classdeclaration appears in the class
definition but the variable definitiondefinition but the variable definition
outside the class in same way asoutside the class in same way as
global variable.global variable.
Example:Example:
75. #
Static Functions
The static member functions are not used very frequently in
programs. But nevertheless, they become useful whenever we
need to have functions which are accessible even when the class
is not instantiated.
Static member functions are considered to have class scope. In
contrast to non-static member functions.
76. #
Differences between a static member function and nonDifferences between a static member function and non
static member functions:static member functions:
1.1. A static member function can access only staticA static member function can access only static
members and data and functions outside the class.members and data and functions outside the class.
2.2. A non-static member function can access all of theA non-static member function can access all of the
above including the static data member.above including the static data member.
1.1. A static member function can be called, even when aA static member function can be called, even when a
class is not instantiated.class is not instantiated.
2.2. A non-static member function can be called only afterA non-static member function can be called only after
instantiating the class as an object.instantiating the class as an object.
77. #
# include <iostream.h># include <iostream.h>
# include <conio.h># include <conio.h>
class gammaclass gamma {{
private:private:
static int total;static int total;
int id;int id;
public:public:
gamma ( ){gamma ( ){
total++;total++;
id=total; }id=total; }
static void showtotal( )static void showtotal( )
{cout<<“Total: ”<<total; }{cout<<“Total: ”<<total; }
void showid()void showid()
{ cout<<“id:” <<id; }{ cout<<“id:” <<id; }
};};
int gamma :: total = 0;int gamma :: total = 0;
void main( )void main( )
{{
clrscr();clrscr();
gamma g1;gamma g1;
gamma :: showtotal();gamma :: showtotal();
gamma g2,g3;gamma g2,g3;
gamma :: showtotal();gamma :: showtotal();
g1.showid();g1.showid();
g2.showid();g2.showid();
g3.showid();g3.showid();
cout<<“END OF PROGRAM”;cout<<“END OF PROGRAM”;
getch( );getch( );
}}
ExampleExample::
78. #
INHERITANCE
• Inheritance is another key feature of Object Oriented
Programming (OOP).
• When creating a class, instead of writing completely
new data members and member functions, the
programmer can designate that the new class should
inherit the members of an existing class.
• This existing class is called Base Class and the new
class is called Derived Class.
80. #
Inheritance relationship form treelike hierarchical structures as shown
below. A class can be Base Class, Derived Class or both.
Shape
TwoDimensional
e
ThreeDimensional
Circle Square Cube Sphere
83. #
Assignment
• Make a class of vehicle as a base class, derive
classes of motorbike, car, truck, crains, lifters
from the vehicle class. Write a program that
will generate the list of any type of vehicle
according to the choice plus the user can also
search the desired vehicle by its company
name say user can search all cars of Toyota
etc.
84. #
MULTIPLE INHERITANCE
A class can be derived from more than one class.
class A
{ };
class B
{ };
class C : public A, public B
{ };
85. #
Class Assignment
• Create Two Base Classes “Personal” and
“Official”.
• Personal: Fname, Lname, Age, HomeAddress
• Official: OfficeAddress, Publications,
87. #
VIRTUAL FUNCTIONS
• Virtual means existence in appearance but not in reality.
• Uses to override the base class function.
Class shape
shape* ptr[100]; //array of 100 pointers to shapes
for (int j=0; j<N; j++)
ptr[j]->draw();
• Completely different functions are executed by the same
function call. If the pointer in ptr points to a ball, the function
that draws a ball is called; if it points to a triangle, the triangle
drawing function is called.
88. #
Main Features:
C++ virtual function is,
• A member function of a class.
• Declared with virtual keyword.
• Usually has a different functionality in the
derived class.
• A function call is resolved at run-time.
89. #
# include <iostream.h># include <iostream.h>
# include <conio.h># include <conio.h>
Class Base {Class Base {
public:public:
void show( )void show( )
{ cout<<”nBase”; }{ cout<<”nBase”; }
};};
Class Derv1: public Base {Class Derv1: public Base {
public:public:
void show( )void show( )
{ cout<<”nDerv1”; }{ cout<<”nDerv1”; }
};};
Class Derv2: public Base {Class Derv2: public Base {
public:public:
void show( )void show( )
{ cout<<”nDerv2”; }{ cout<<”nDerv2”; }
};};
void main( ){void main( ){
Derv1 dv1;Derv1 dv1;
Derv2 dv2;Derv2 dv2;
Base* ptr;Base* ptr;
ptr = &dv1;ptr = &dv1; ptr->show();ptr->show();
ptr = &dv2;ptr = &dv2; ptr->show();ptr->show();
getch();getch();
}}
Note:Note: Pointers to objects of derivedPointers to objects of derived
class are type compatible withclass are type compatible with
pointers to objects of base class.pointers to objects of base class.
The output of this program isThe output of this program is
ExampleExample (Member Functions accessed with pointers(Member Functions accessed with pointers::
BaseBase
BaseBase
90. #
# include <iostream.h># include <iostream.h>
# include <conio.h># include <conio.h>
Class Base {Class Base {
public:public:
virtualvirtual void show( )void show( )
{ cout<<”nBase”; }{ cout<<”nBase”; }
};};
Class Derv1: public Base {Class Derv1: public Base {
public:public:
void show( )void show( )
{ cout<<”nDerv1”; }{ cout<<”nDerv1”; }
};};
Class Derv2: public Base {Class Derv2: public Base {
public:public:
void show( )void show( )
{ cout<<”nDerv2”; }{ cout<<”nDerv2”; }
};};
void main( ){void main( ){
Derv1 dv1;Derv1 dv1;
Derv2 dv2;Derv2 dv2;
Base* ptr;Base* ptr;
ptr = &dv1;ptr = &dv1; ptr->show();ptr->show();
ptr = &dv2;ptr = &dv2; ptr->show();ptr->show();
getch();getch();
}}
The output of this program isThe output of this program is
ExampleExample (Virtual Member Functions accessed with pointers)(Virtual Member Functions accessed with pointers)::
Derv1Derv1
Derv2Derv2
91. #
DYNAMIC AND STATIC BINDING:
• ptr->show( ); it always compiles a call to the show( ) function
in the base class.
• Using “virtual” keyword with function in base class, the compiler
doesn’t know what class the content of ptr may contain.
• It could be address of an object of the Derv1 or of the Derv2 class.
• Compiler arranges for the decision to be deferred until the program
is running.
• At runtime when it is known that what class is pointed to by ptr, the
appropriate version of show function will be called.
• This is called LATE BINDING or DYNAMIC BINDING. (Choosing
functions in the normal way, during compilation is called EARLY
BINDING or STATIC BINDING).
92. #
ABSTRACT CLASS:
• When one never want to instantiate objects of the
base class, we call it an abstract class.
• Such a class exists only to act as a parent of
derived classes that will be used to instantiate
objects.
• An abstract class consists of at least one pure
virtual function.
93. #
PURE VIRTUAL FUNCTION:
• A pure virtual function is one with the expression =0 added to the
declaration. e.g.
virtual void getData() = 0;
• Now if one try to attempt to create objects of the base class, the
compiler will complain that you are trying to instantiate an object of
the abstract class.
• Once one placed a pure virtual function in the base class, one must
override it in all the derived classes from which one want to
instantiate objects.
• If a class does not override the pure virtual function, it becomes an
abstract class itself, and one cannot instantiate objects from it.
94. #
# include <iostream.h># include <iostream.h>
# include <conio.h># include <conio.h>
class person {class person {
protected:protected:
char name[40];char name[40];
public:public:
void getName( )void getName( )
{ cout<<”Enter name: ”; cin>>{ cout<<”Enter name: ”; cin>>
name; }name; }
void putName( )void putName( )
{cout<<”Name is” << name << endl;}{cout<<”Name is” << name << endl;}
virtual void getData( ) = 0;virtual void getData( ) = 0;
virtual bool isOutstanding()=0;virtual bool isOutstanding()=0;
};};
class student: public person {class student: public person {
private: float gpa;private: float gpa;
public:public:
void getData( )void getData( )
{{ person::getName( );person::getName( );
cout<<”nEnter student’s GPA:”;cout<<”nEnter student’s GPA:”;
cin >> gpa; }cin >> gpa; }
bool isOutstanding( )bool isOutstanding( )
{{ return (gpa > 3.5) ? true :return (gpa > 3.5) ? true :
false; }false; } };};
Class professor: public person {Class professor: public person {
private: int numPubs;private: int numPubs;
public:public:
void getData( )void getData( )
{{ person::getName();person::getName();
cout<<”nEnter No. of Publications: ”;cout<<”nEnter No. of Publications: ”;
cin >> numPubs; }cin >> numPubs; }
bool isOutstanding( )bool isOutstanding( ) {{
return (numPubs > 100) ?return (numPubs > 100) ?
true : false; }true : false; } };};
ExampleExample::
95. #
void main( ) {void main( ) {
person* persPtr[100];person* persPtr[100];
int n = 0; char choice;int n = 0; char choice;
do {do {
cout <<”nEnter student or professorcout <<”nEnter student or professor
(s/p):”; cin >> choice;(s/p):”; cin >> choice;
if (choice ==’s’)if (choice ==’s’)
persPtr[n] = new student;persPtr[n] = new student;
Else persPtr[n] = new professor;Else persPtr[n] = new professor;
persPtr[n++]->getData();persPtr[n++]->getData();
cout<<”Enter Another ? (y/n):”;cout<<”Enter Another ? (y/n):”;
cin>>choice;cin>>choice;
} while (choice == ‘y’);} while (choice == ‘y’);
for (int j=0; j<n; j++) {for (int j=0; j<n; j++) {
persPtr[j]->putName( );persPtr[j]->putName( );
if ( persPtr[j]->isOutstanding() )if ( persPtr[j]->isOutstanding() )
cout<<”nThis person is outstanding”;}cout<<”nThis person is outstanding”;}
getch(); }getch(); }
OUTPUT:OUTPUT:
Enter student or professor (s/p): sEnter student or professor (s/p): s
Enter Name: OvaisEnter Name: Ovais
Enter student’s GPA: 1.2Enter student’s GPA: 1.2
Enter Another ? (y/n): yEnter Another ? (y/n): y
Enter student or professor (s/p): pEnter student or professor (s/p): p
Enter Name: UsmanEnter Name: Usman
Enter number of publications: 712Enter number of publications: 712
Enter Another ? (y/n): yEnter Another ? (y/n): y
Enter student or professor (s/p): pEnter student or professor (s/p): p
Enter Name: WaqasEnter Name: Waqas
Enter number of publications: 71Enter number of publications: 71
Enter Another ? (y/n): nEnter Another ? (y/n): n
Name is: OvaisName is: Ovais
Name is: UsmanName is: Usman
This person is outstandingThis person is outstanding
Name is: WaqasName is: Waqas
Example (Contd.)Example (Contd.) ::
96. #
Assignment Deadline:
• Write a program using Polymorphism Technique to
define the class of person as a base class and hence
derive student and employee classes from it. Then
derive classes from employee class such as lecturer,
director, clerk or accountant etc. The program
should then show the list of employees according to
their categories and students showing their details.
• Q2-Extend the above program to sort the lists of
employees of all categories and also the list of
students.
97. #
EXCEPTION HANDLING
• Exception is an unusual condition which affects
the normal flow of program.
• The code that intercepts an exception is called a
handler.
• Exception Handling is a way in which a program
encounters an unusual situation and it tries to
solve that unusual situation.
• These unwanted errors could be user, logic or
system errors that can be detected by a function.
98. #
• In C++, when an exception is thrown, it cannot be
ignored.
• If no user provided exception handler is present, the
compiler provides a default exception handler to
terminate the program.
EXAMPLE :
int cal (int a, int b)
{return a/b;}
Solution:
int cal (int a, int b)
{
if (b==0)
exit (1);
return a/b;}
NOT AN ELEGANT SOLUTION
99. #
Exception Syntax:
• Any code in the application that uses objects of the class is
enclosed in a “Try block”.
• The application makes a mistake, causing an error to be detected
in a member function.
• Member function then informs the application that an error has
occurred (“Throwing an Exception”).
• In the application we add a separate section of code to handle the
error, called as “Exception Handler or Catch Block”. It must
immediately follow the try block.
• THE ERROR GENERATED IN THE TRY BLOCK WILL BE CAUGHT IN
THE CATCH BLOCK.
100. #
Exception Syntax (Contd.):
Class AClass {
public:
void Func( )
{ if (error condition)
throw Exception;
}
};
void main( ) {
try
{ // code to be tried. }
catch (type Exception)
{ // code to be executed in case of exception }
getch( ); }
101. #
TRY BLOCK
try
{ // code to be tried.
throw exception; }
• The try block starts with keyword ”try”.
• The try block surrounds statement in which
exception may be thrown.
• throw statement transfers control of the program
to the catch block.
102. #
CATCH BLOCK
catch (char const* message)
{ // code to handle the exception. }
• The catch block contains the code which will execute when
an exception will throw.
• Since exceptions are thrown, the catch block must know
what kind of exceptions it should be able to handle.
Therefore the keyword catch is followed by a parameter.
• In catch block parentheses more than one parameter are
not allowed.
103. #
Sequence of Events:
1. Code is executing normally outside the try
block.
2. Control enters the try block.
3. A statement in the try block causes an error
in a member function.
4. The member function throws an exception.
5. Control transfers to the exception handler
(catch block).
104. #
Single and Multiple Exception
• If there is only one try and catch block, it will
called as “Single Exception”.
• If there are more than one catch blocks with
the one try block then it will be called as
“Multiple Exception”.
105. #
SINGLE EXCEPTION:SINGLE EXCEPTION:
In this program we will throw anIn this program we will throw an
exception whenever a number isexception whenever a number is
divided by zero.divided by zero.
************************************************
#include<iostream>#include<iostream>
#include<conio.h>#include<conio.h>
usng namespace std;usng namespace std;
void main()void main()
{{
int x= 5;int x= 5;
int y = 0;int y = 0;
int result;int result;
try {try {
if (y == 0)if (y == 0)
throw “Divide by Zero”;throw “Divide by Zero”;
result = x / y;result = x / y;
}}
catch (char * e)catch (char * e)
{{
cout << e << endl;cout << e << endl;
}}
cout<< “GOODBYE!”<< endl;cout<< “GOODBYE!”<< endl;
getch();getch();
}}
106. #
MULTIPLE EXCEPTIONS:MULTIPLE EXCEPTIONS:
using namespace std;using namespace std;
class Stack{class Stack{
private:private:
int st[3]; int top;int st[3]; int top;
public:public:
Stack( )Stack( )
{top= -1;}{top= -1;}
void push(int var) {void push(int var) {
if (top>=2)if (top>=2)
throw top;throw top;
st[++top]=var;st[++top]=var;
cout<<st[top]<<endl; }cout<<st[top]<<endl; }
int pop( ) {int pop( ) {
if (top<0)if (top<0)
throw "STACK IS EMPTY";throw "STACK IS EMPTY";
return st[top--]; } };return st[top--]; } };
void main( ) {void main( ) {
Stack s1;Stack s1;
try{try{
s1.push(111);s1.push(111);
s1.push(222);s1.push(222);
s1.push(333);s1.push(333);
//s1.push(444);//s1.push(444);
cout<<s1.pop()<<endl;cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;cout<<s1.pop()<<endl;
}}
catch (char * e)catch (char * e)
{{ cout<<e<<endl;cout<<e<<endl; }}
catch (int top)catch (int top)
{{cout<<"Stack is Full:top="<<top;cout<<"Stack is Full:top="<<top;}}
getch(); }getch(); }
107. #
1) throw top;
2) throw “Stack is Empty”;
• 1st
Part of this statement transfers program
control to the exception handler (catch block).
• 2nd
Part of this statement passes as arguments
to the catch block.
108. #
TEMPLATES
Template make it possible to use one function or class to
handle many different data types.
The template function can be used in two different ways:
Template Functions
Template Classes.
109. #
TEMPLTE FUNCTIONS:
Template Functions are used to perform identical
operations for each type of data compactly and
conveniently.
One can write a single function template definition.
Based on the argument types provided in calls to the
function, the compiler automatically instantiates separate
object code functions to handle each type of call
appropriately.
The amount of RAM used by the program is the same
whether we use the template approach or not.
110. #
#include <iostream.h>
#include <conio.h>
//max returns the maximum of the two elements
template <class T>
T max (T a, T b)
{ return a > b ? a : b ; }
void main() {
cout << "max int= " << max (10, 15) << endl ;
cout << "max char= " << max ('k', 's') << endl ;
cout << "max float= " << max(10.1, 15.2) << endl ;
}
Program Output
max int = 15
max char = s
max float = 15.2
111. #
• The key point in function template is to
represent the data type used by the function
not as a specific type such as int, but by a
name that can stand for any type.
• The template keyword signals the compiler
that we are about to define a function
template. The keyword class can be called as
type.
• The variable following the keyword class (T in
example) is called the template argument.
112. #
#include<iostream.h>
#include<conio.h>
template <class T>
T sq (T var)
{ return var*=var; }
void main( )
{
clrscr ( );
int i1=5;
float f1=10.5;
long l1=125;
int v1=sq(i1);
cout<<v1<<endl;
float v2=sq(f1);
cout<<v2<<endl;
long v3=sq(l1);
cout<<v3;
getch();
}
Example 1Example 1::
113. #
Class Assignment
• Write a template function which gives the absolute
value of any given input variable. Input variables
might be of data type int, long, double, float etc.
• Create 03 arrays of different data types and of
different lengths. Write a template function which
take array, size of array and value to be searched in
an array as parameters. Print the index at which
value is found or “value not found” accordingly.
114. #
TEMPLTE CLASS:
• One C++ Class Template can handle different types of
parameters.
• Compiler generates classes for only the used types. If the
template is instantiated for int type, compiler generates
only an int version for the c++ template class.
• Templates reduce the effort on coding for different data
types to a single set of code.
• Testing and debugging efforts are reduced.
• Class template are generally use for data storage classes.
115. #
#include<iostream.h>
#include<conio.h>
template <class T>
class Bahria{
private:
T var;
public:
T sq (T var)
{ return var*=var; }
};
void main( ){
Bahria<int> b1;
int i=10;
int v1=b1.sq(i);
cout<<v1<<endl;
Bahria<float> b2;
float f=10.5;
float v2=b2.sq(f);
cout<<v2<<endl;
Bahria<long> b3;
long l=125;
long v3=b3.sq(l);
cout<<v3; }
Example:
117. #
Streams and Files
Stream classes:
• A stream is general name given to a flow of
data.
• In C++ a stream is represented by an object of
a particular class.
• So far, we have used cin and cout stream
objects.
• Different streams are used to represent
different kind of data flow. e.g. ifstream class
represents data flow from input disk files.
119. #
The classes used for input and output to theThe classes used for input and output to the
video display and keyboard are declared in thevideo display and keyboard are declared in the
header file IOSTREAM.header file IOSTREAM.
The classes used specifically for disk file I/OThe classes used specifically for disk file I/O
are declared in the file FSTREAM.are declared in the file FSTREAM.
istream and ostream perform input andistream and ostream perform input and
output specific activities respectively.output specific activities respectively.
These classes consist of a number of functionsThese classes consist of a number of functions
e.g. open, close, get, write, read, getline, pose.g. open, close, get, write, read, getline, pos
etc.etc.
120. #
• C++ provides the following classes to perform
output and input of characters to/from files:
• ofstream: Stream class to write on files
• ifstream: Stream class to read from files
• fstream: Stream class to both read and write from/to files.
121. #
Opening a file
• In order to create/open a file with a stream object we use its
member function open( ):
• open (filename, mode);
mode is an optional parameter with a combination of the
following flags:
– ios::in Open for input operations.
– ios::out Open for output operations.
– ios::app All output operations are performed at the end of the file,
appending the content to the current content of the file.
ofstream myfile;
myfile.open("c:/text.txt", ios::out);
Closing a file
myfile.close( );
122. #
Advantages of Stream:
• Simplicity.
• One can overload existing operators and
functions such as << and >> operators.
• Best way to write data to files.
• Best way to format data in memory for later
use in text input/output windows and other
GUI elements.
123. #
#include<iostream>#include<iostream>
#include<conio.h>#include<conio.h>
#include<fstream>#include<fstream>
#include<string>#include<string>
using namespace std;using namespace std;
void main ( ) {void main ( ) {
ofstream out;ofstream out;
int a1; int a2;int a1; int a2;
int result; int count=0;int result; int count=0;
cout<<"Enter 1st Number: ";cout<<"Enter 1st Number: ";
cin>>a1;cin>>a1;
bck : try{bck : try{
cout<<"Enter 2nd Number: ";cout<<"Enter 2nd Number: ";
cin>>a2;cin>>a2;
if (a2==0)if (a2==0)
throw a2;throw a2;
elseelse
result= a1/a2;result= a1/a2;
out.open("c:/text.txt", ios::out);out.open("c:/text.txt", ios::out);
if (out)if (out)
{{
out<<"Result ofout<<"Result of
"<<a1<<"/"<<a2<<" ="<<a1<<"/"<<a2<<" =
"<<result<<endl;"<<result<<endl;
cout<<"File Created and Resultcout<<"File Created and Result
Saved"<<endl;Saved"<<endl;
}}
elseelse
cout<<"not created";cout<<"not created";
out.close();out.close();
}}
catch (int a)catch (int a)
{{
count++;count++;
cout<<"Error Occurs: Value of a2=cout<<"Error Occurs: Value of a2=
"<<a<<endl;"<<a<<endl;
if(count<=2)if(count<=2)
goto bck;goto bck;
}}
}}
124. #
Class Assignment
• Create a file “BET” which saves the following
data of any 10 students of class.
FName, LName, Age, Id, CGPA, DOB,
PlaceOfBirth, FavGame, FavFood, FavColor.
125. #
Access Specifiers:
public: can be used anywhere without the
access restrictions defined by private or
protected.
private: can be used only by the members and
friends of class A.
protected: can be used only by the members
and friends of class A, and the members and
friends of classes derived from class A.
A friend of a class X is a function or class
that is not a member of X, but is granted the
same access to X as the members of X.
126. #
class def{class def{
float condition,x,y,z;float condition,x,y,z;
public:public:
def( ){def( ){
cout<<"Enter the condition: ";cout<<"Enter the condition: ";
cin>>condition;}cin>>condition;}
void func1( ){void func1( ){
if(condition==1){if(condition==1){
cout<<"Enter length of one side of square: ";cout<<"Enter length of one side of square: ";
cin>>x;cin>>x;
x*=x;x*=x;
mydef(x);}mydef(x);}
if(condition==2){if(condition==2){
cout<<"Enter length of rectangle: ";cout<<"Enter length of rectangle: ";
cin>>x;cin>>x;
cout<<"Enter width of rectangle: ";cout<<"Enter width of rectangle: ";
cin>>y;cin>>y;
mydef(x,y); }mydef(x,y); }
if (condition==3) {if (condition==3) {
cout<<"Enter height of triangle: ";cout<<"Enter height of triangle: ";
cin>>x;cin>>x;
cout<<"Enter base of triangle: ";cout<<"Enter base of triangle: ";
cin>>y;cin>>y;
z=0.5;z=0.5;
mydef(x,y,z);}}mydef(x,y,z);}}
void mydef(float x=1,float y=1, float z=1);void mydef(float x=1,float y=1, float z=1);
};};
void def::mydef(float x1,float y1, float z1)void def::mydef(float x1,float y1, float z1)
{{
float result;float result;
result=x1*y1*z1;result=x1*y1*z1;
cout<<"nResult: "<<result<<endl;cout<<"nResult: "<<result<<endl;
}}
void main()void main()
{ def d;{ def d;
d.func1( ); }d.func1( ); }