SlideShare une entreprise Scribd logo
1  sur  72
CHAPTER -4
Structure and Class
After covering this unit you will understand…
• Structures
– Structure types
– Structures initialization
– Initializing structures
• Classes
– Defining, member functions
– Public and private members
– Accessor and mutator functions
– Structures vs. classes
1
Structure
• A Structure is a collection of related data items,
possibly of different types.
• A structure type in C++ is called struct.
• A struct is heterogeneous in that it can be composed of
data of different types.
• In contrast, array is homogeneous since it can contain
only data of the same type.
• Structures hold data that belong together.
• Examples:
– Student record: student id, name, major, gender, start year, …
– Bank account: account number, name, currency, balance, …
– Address book: name, address, telephone number, …
• In database applications, structures are called
records(columns).
2
Structure
• Individual components of a struct type are called
members (or fields).
• Members can be of different types (simple, array or
struct).
• A struct is named as a whole while individual
members are named using field identifiers.
• Complex data structures can be formed by defining
arrays of structs.
• A structure is collection of variables and methods
3
structure
• Before a structure can be used, it must be declared.
Here is the general format of a structure declaration:
struct tag
{
variable declaration;
// ... more declarations
//may follow...
};
• The tag is the name of the structure. it’s used like a
data type name.
• The variable declarations that appear inside the braces
declare members of the structure.
4
Declaring structure
• struct keyword is used for declaration
• In a structure, variables can have different data
types
• Can have private, protected and public access
specifiers
• The default access specifier is public
• Semicolon “;” comes in the end to complete
structure declaration
5
Cont’d…
struct Student{
char name;
int batch
int Id;
int age;
char sex;
double CGA;
};
struct Date {
int day;
int month;
int year;
} ;
The “Student”
structure has 6
members
of different types.
While in database , struct name student is termed
as”main database table name” and the variables
listed are said to be “records” with the same data
types
The “Date” structure
has 3 members,
day, month & year.
6
Cont’d…
struct employee
{
string firstName;
string lastName;
string address1;
string address2;
double salary;
string deptID;
};
defines a struct employee with six
members. The members firstName,
lastName, address1, address2, and
deptID are of type string, and the
member salary is of type double.
Like any type definition, a struct is a
definition, not a declaration. That is, it
defines only a data type; no memory is
allocated.
7
Accessing struct Members
• In arrays, you access a element by using the array
name together with the relative position (index) of
the component. The array name and index are
separated using square brackets.
• To access a structure member (component), you
use the struct variable name together with the
member name; these names are separated by a dot
(period). The syntax for accessing a struct member is:
structVariableName.memberName
8
.dot operator
• C++ provides the dot operator (a period) to access
the individual members of a structure.
• the following statement demonstrates how to
access the salary member:
Employee.salary = 475;
• In this statement, the number 475 is assigned to the
salary member of employee.
• The dot operator connects the name of the
member variable with the name of the structure
variable it belongs to.
9
Cont’d…
• The following statements assign values to the
empNumber members of the deptHead, foreman,
and associate structure variables:
deptHead.empNumber = 78;
foreman.empNumber = 897;
associate.empNumber = 729;
10
Cont’d…
• With the dot operator you can use member
variables just like regular variables.
• For example these statements display the contents
of deptHead’s members:
cout << deptHead.empNumber << endl;
cout << deptHead.name << endl;
cout << deptHead.hours << endl;
cout << deptHead.payRate << endl;
cout << deptHead.grossPay << endl;
11
Cont’d…
#include<iostream.h>
struct telephone
{
char *name;
int number;
};
int main()
{
struct telephone index;
index.name = "Jane Monroe";
index.number = 12345;
cout << "Name: " << index.name << 'n';
cout << "Telephone number: " << index.number;
return 0;
}
12
Initializing a Structure
• The members of a structure variable may
be initialized with starting values when
the structure variable is declared.
struct GeoInfo
{
char cityName[30];
char state[3];
long population;
int distance;
};
GeoInfo location = {“Ashville”, “NC”, 50000, 28}; 13
Struct example
#include<iostream.h>
struct Date
{
int month;
int day;
int year;
};
void main()
{
//Date dueDate;
Date dueDate = {12, 31, 2003};
cout<< dueDate.month <<endl;
cout<< dueDate.day <<endl;
cout<< dueDate.year << endl;
}
14
Cont’d…
#include <iostream.h>
struct PayRoll
{
int empNumber; // Employee number
char name[25]; // Employee's name
float hours; // Hours worked
float payRate; // Hourly Payrate
float grossPay; // Gross Pay
};
void main(void)
{
PayRoll employee;/*Employee is a PayRoll structure or employee is a structure variable name and empnumber---gross pay are calledmembers
of the structure called payroll */
cout << "Enter the employee's number: ";
cin >> employee.empNumber;
cout << "Enter the employee's name: ";
cin.ignore(); // To skip the remaining 'n' character
cin.getline(employee.name, 25);
cout << "How many hours did the employee work? ";
cin >> employee.hours;
cout << "What is the employee's hourly payrate? ";
cin >> employee.payRate;
employee.grossPay = employee.hours * employee.payRate;
cout << "Here is the employee's payroll data:n";
cout << "Name: " << employee.name << endl;
cout << "Number: " << employee.empNumber << endl;
cout << "Hours worked: " << employee.hours << endl;
cout << "Hourly Payrate: " << employee.payRate << endl;
cout << "Gross Pay: $" << employee.grossPay << endl;
}
15
Struct example
#include <iostream.h>
#include <math.h> // For the pow function?
#include <iomanip.h>
// Constant for pi.
const double PI = 3.14159;
// Structure declaration
struct Circle
{
double radius; // A circle's radius
double diameter; // A circle's diameter
double area; // A circle's area
};
int main()
{
Circle c; // Define a structure variable; circle =structure name;c = struct variable name
// Get the circle's diameter.
cout << "Enter the diameter of a circle: ";
cin >> c.diameter;
// Calculate the circle's radius.
c.radius = c.diameter / 2;
// Calculate the circle's area.
c.area = PI * pow(c.radius, 2.0);
// Display the circle data.
//cout << fixed << showpoint << setprecision(2);
cout << "The radius and area of the circle are:n";
cout << "Radius: " << c.radius << endl;
cout << "Area: " << c.area << endl;
return 0;
}
16
Assignment in struct
• We can assign the value of one struct variable to
another struct variable of the same type by using an
assignment statement.
17
Cont’d..
The statement:
student = newStudent;
• copies the contents of newStudent into student.
18
Cont’d…
In fact, the assignment statement:
student = newStudent;
is equivalent to the following statements:
student.firstName = newStudent.firstName;
student.lastName = newStudent.lastName;
student.courseGrade = newStudent.courseGrade;
student.testScore = newStudent.testScore;
student.programmingScore =
newStudent.programmingScore;
student.GPA = newStudent.GPA;
19
Cont’d…
#include <iostream.h>
#include <iomanip.h>
struct student
{
char st_name[25];
char grade;
int age;
float average;
};
void main()
{
student std1 = {"Joe Brown", 'A', 13, 91.488888};
struct student std2, std3; // Not initialized
std2 = std1; // Copies each member of std1
std3 = std1; // to std2 and std3.
cout << "The contents of std2:n";
cout << std2.st_name << " " << std2.grade <<" ";
cout << std2.age << " " << std2.average << "nn";
cout << "The contents of std3:n";
cout << std3.st_name << " " << std3.grade << " ";
cout << std3.age << " " << std3.average << "n";
return;
}
20
Nested Structures
• C++ gives you the ability to nest one structure
definition in another.
• You have to define the common members only once
in their own structure and then use that structure
as a member in another structure.
• Nesting of structures is placing structures within structure.
21
Cont’d…
• When a structure is declared as the member of another structure, it is
called Structure within a structure. It is also known as nested structure.
Example of nested structure
One example of nested structure is given below:
struct date
{
// members of structure
int day;
int month;
int year;
};
struct company
{
char name[20];
long int employee_id;
char sex[5];
int age;
struct date dob;};
22
Cont’d…
#include<iostream.h>
#include<string.h>
#define MAX 1000
// structure block defination
struct date{
// members of structure definition
int day;
int month;
int year;
};
struct company{
char name[20];
long int employee_id;
char sex[5];
int age;
// nested block defination
struct date dob;
};
// structuer object defination
company employee[MAX];
// main function starts
int main(){
company employee[MAX];
int n;
cout << "A program for collecting employee information";
cout << endl;
cout << "And displaying the collected information";
cout << endl << endl;
cout << "How many employees:";
cin >> n;
cout << endl;
// functions defination
void CollectInformtion(company employee[MAX], int n);
void Display(company employee[MAX], int n);
// functions calling
CollectInformtion(employee, n);
Display(employee, n);
cin.get();
return 0;
}
// collecting information form the user
void CollectInformtion(company employee[MAX], int n){
cout << "Enter the following information:";
cout << endl << endl;
for (int i=1; i<=n; i++){
cout << "Enter information for employee no: " << i;
cout << endl;
cout << "Name :"; cin >> employee[i].name;
cout << "ID :"; cin >> employee[i].employee_id;
cout << "Sex :"; cin >> employee[i].sex;
cout << "Age :"; cin >> employee[i].age;
cout << "Date of Birth:" << endl;
cout << "Day :"; cin >> employee[i].dob.day;
cout << "Month :"; cin >> employee[i].dob.month;
cout << "Year :"; cin >> employee[i].dob.year;
cout << endl;
}
}
// displaying entered information to the standard output
void Display(company employee[MAX], int n){
cout << "Employee entered information:";
cout << endl;
cout << "Name ID Sex Age
Date of Birth" << endl;
for (int i=1; i<=n; i++){
cout << employee[i].name << "t";
cout << employee[i].employee_id << "t";
cout << employee[i].sex; cout << "t";
cout << employee[i].age; cout << "t";
cout << employee[i].dob.day << ".";
cout << employee[i].dob.month << ".";
cout << employee[i].dob.year ;
cout << endl;
}
}
23
Cont’d…
#include <iostream.h>
struct Date
{
int month;
int day;
int year;
};
struct Place
{
char address[50];
char city[20];
char state[15];
char zip[11];
};
struct EmpInfo
{
char name[50];
int empNumber;
Date birthDate;
Place residence;
};
void main(void)
{
EmpInfo manager;
// Ask for the manager's name and employee number
cout << "Enter the manager's name: ";
cin.getline(manager.name, 50);
cout << "Enter the manager's employee number: ";
cin >> manager.empNumber;
24
Cont’d…
// Get the manager's birth date
cout << "Now enter the manager's date-of-birth.n";
cout << "Month (up to 2 digits): ";
cin >> manager.birthDate.month;
cout << "Day (up to 2 digits): ";
cin >> manager.birthDate.day;
cout << "Year (2 digits): ";
cin >> manager.birthDate.year;
cin.get(); // Eat the remaining newline character
// Get the manager's residence information
cout << "Enter the manager's street address: ";
cin.getline(manager.residence.address, 50);
cout << "City: ";
cin.getline(manager.residence.city, 20);
cout << "State: ";
cin.getline(manager.residence.state, 15);
cout << "Zip Code: ";
cin.getline(manager.residence.zip, 11);
// Display the information just entered
cout << "nHere is the manager's information:n";
cout << manager.name << endl;
cout << "Employee number " << manager.empNumber << endl;
cout << "Date of Birth: ";
cout << manager.birthDate.month << "-";
cout << manager.birthDate.day << "-";
cout << manager.birthDate.year << endl;
cout << "Place of residence:n";
cout << manager.residence.address << endl;
cout << manager.residence.city << ", ";
cout << manager.residence.state << " ";
cout << manager.residence.zip << endl;
}
25
Strings as Structure Members
When a character array is a structure member, use
the same sting manipulation techniques with it as
you would with any other character array.
26
Cont’d…
#include <iostream.h>
#include <string.h>
struct Name
{
char first[15];
char middle[15];
char last[15];
char full[45];
};
void main(void)
{
Name person;
cout << "Enter your first name: ";
cin >> person.first;
cout << "Enter your middle name: ";
cin >> person.middle;
cout << "Enter your last name: ";
cin >> person.last;
strcpy(person.full, person.first);
strcat(person.full, " ");
strcat(person.full, person.middle);
strcat(person.full, " ");
strcat(person.full, person.last);
cout << "nYour full name is " << person.full << endl;
}
27
Arrays of Structures
• Arrays of structures can simplify some programming
tasks.
struct BookInfo
{
char title[50];
char author[30];
char publisher[25];
float price;
};
BookInfo bookList[20];
28
class
• Class is a collection of data member and member function.
Objects are also called instance of the class.
• A class is similar to a structure. It is a data type defined by the
programmer, consisting of variables and functions.
• Each object contains all members(variables and functions)
declared in the class.
• We can access any data member or member function
from object of that class using .
• A class is the collection of related data and function under a
single name.
• A C++ program can have any number of classes. When related
data and functions are kept under a class, it helps to visualize
the complex problem efficiently and effectively.
29
A Class is a blueprint for objects
When a class is defined, No Memory Is Allocated. You can imagine
like a data type.
int var;
The above code specifies var is a variable of type integer;
int is used for specifying variable var is of integer type.
Similarly, class are also just the specification for objects
and object bears the property of that class.
A class specification has two parts :
1) Class declaration
2) Class Function Definitions
30
Cont’d…
A class definition starts with the
keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces. A
class definition must be followed either by a
semicolon or a list of declarations
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box }; 31
class
• The keyword public determines the access
attributes of the members of the class that follow it.
• A public member can be accessed from outside the
class anywhere within the scope of the class object.
You can also specify the members of a class
as private or protected .
32
Define C++ Objects:
• A class provides the blueprints(sth acts as template for sth) for
objects, so basically an object is created from a
class.
• We declare objects of a class with exactly the same
sort of declaration that we declare variables of basic
types. Following statements declare two objects of
class Box:
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
33
Accessing the Data Members:
The public data members of objects of a class can be
accessed using the direct member access operator
(.).
34
Cont’d…
#include <iostream>
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main( )
{ Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0; // box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0; // volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl; // volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl; return 0; }
35
Access Specifiers
• C++ provides the key words private and public which you may
use in class declarations.
• These key words are known as access specifiers because they
specify how class members may be accessed. The following is
the general format of a class declaration that uses the private
and public access specifiers.
class ClassName
{
private:
// Declarations of private
// members appear here.
public:
// Declarations of public
// members appear here.
};
36
Cont’d…
37
Cont’d…
• The keyword class specifies user defined data type class name
• The body of a class is enclosed within braces and is terminated by
a semicolon
• The class body contains the declaration of variables and functions
• The class body has three access specifiers ( visibility labels) viz.,
private , public and protected
• Specifying private visibility label is optional. By default the
members will be treated as private if a visibility label is not
mentioned
• The members that have been declared as private, can be accessed
only from within the class
• The members that have been declared as protected can be
accessed from within the class, and the members of the inherited
classes.
• The members that have been declared as public can be accessed
from outside the class also
38
Data Abstraction
• The binding of data and functions together into a single
entity is referred to as encapsulation.
• The members and functions declared under private are not
accessible by members outside the class, this is referred to
as data hiding.
• Instruments allowing only selected access of components
to objects and to members of other classes is called as Data
Abstraction. Or rather Data abstraction is achieved through
data hiding.
39
Data Members and Member Functions
• Class comprises of members. Members are further
classified as Data Members and Member functions.
Data members are the data variables that represent
the features or properties of a class.
• Member functions are the functions that perform
specific tasks in a class.
• Member functions are called as methods, and data
members are also called as attributes.
40
Cont’d…
41
Accessors and Mutators
• A member function that gets a value from a class’s
member variable but does not change it is known as an
accessor.
• A member function that stores a value in member
variable or changes(mutates) the value of member variable
in some other way is known as a mutator.
• In the Rectangle class, the member functions getLength
and getWidth are accessors, and the member functions
setLength and setWidth are mutators.
• Some programmers refer to mutators as setter
functions because they set the value of an attribute,
and accessors as getter functions because they get the
value of an attribute.
42
Cont’d…
#include <iostream>
class Rectangle
{
int width, height;
public:
void set values(int,int); //mutator
int area ()
{
return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x; height = y; }
int main ()
{
Rectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0; } 43
Creating Objects
• declaration statement student stud; This statement
may be read as stud is an instance or object of the
class student. Syntax for object declaration.
• Once a class has been declared, variables of that type
can be declared. ‘stud’ is a variable of type student
,student is a data type of class .
• In C++ the class variables are known as objects. The
declaration of an object is similar to that of a variable
of any basic type.
• Objects can also be created by placing their names
immediately after the closing brace of the class
declaration.
44
Cont’d…
• Class objects must be defined after the class is
declared.
Rectangle box;
• ClassName is the name of a class and objectName is
the name we are giving the object.
• Defining a class object is called the instantiation of
a class. In this statement, box is an instance of the
Rectangle class.
45
Accessing an Object’s Members
• The members of a class are accessed using the dot
operator.
• The dot operator is used to connect the object and
the member function.
• For example, the call statement to the function
execute() of the class student may be given as:
box.setWidth(12.7); 46
Defining methods of a class/member functions/
47
Cont’d…
• In Method 1, the member function add() is declared and
defined within class add.
• In Method 2, the member function display() is declared within
the class, and defined outside the class.
• The member function have some special characteristics that
are often used in the program development .
• Several different classes can use the same function name.
The ‘membership’ label will resolve their scope Member
functions can access the private data of a class. A nonmember
function cannot do so.
• A member function can call another member function
directly, without using the dot operator. ( This is called as
nesting of member functions )
• The member functions can receive arguments of a valid C++
data type. Objects can also be passed as arguments
• The return type of a member function can be of object data
type Member functions can be of static type 48
constructor
• A constructor is a member function that is
automatically called when an object of that class is
declared.
• A constructor is used to initialize the values of
some or all member variables and to do any other
sort of initialization that may be needed.
• A constructor is a member function of a class that
has the same name as the class.
• A constructor is called automatically when an object
of the class is declared. Constructors are used to
initialize objects.
• A constructor must have the same name as the
class of which it is a member. 49
CONSTRUCTOR DEFINITIONS
You define a constructor the same way that you
define any other member function, except for two
points:
1. A constructor must have the same name as the
class. For example, if the class is named
BankAccount , then any constructor for this class
must be named BankAccount
2. A constructor definition cannot return a value.
Moreover, no type, not even Void can be given at
the start of the function declaration or in the
function header.
Constructors can be overloaded 50
Cont’d…
class rectangle { // A simple class
int height;
int width;
public:
rectangle(void); // with a constuctor,
~rectangle(void); // and a destructor
};
rectangle::rectangle(void) // constuctor
{
height = 6; width = 6;
}
51
Cont’d…
#include <iostream.h>
// A simple class declaration
class rectangle
{
// private access by default, access only through the method or interface
int height;
int width;
// public
public:
// constructor, initial object construction, allocating storage, initial value etc.
rectangle(void);
// methods, access something, do something
int area(void);
void initialize(int, int);
// destructor, destroy all the object, return resources such as memory etc. to the
system
~rectangle(void);
};
// class implementation
// constructor implementation
rectangle::rectangle(void)
{
// give initial values
height = 6;
width = 6;
}
int rectangle::area(void)
{
// just return the area
return (height * width);
}
void rectangle::initialize(int initial_height, int initial_width)
{
// give initial values
height = initial_height;
width = initial_width;
}
// destructor implementation
rectangle::~rectangle(void)
{
// destroy all the object an return the resources to the system
height = 0;
width = 0;
}
// normal structure - compare with class usage
struct pole
{
int length;
int depth;
};
// comes the main()
void main(void)
{
// class object instantiations
rectangle wall, square;
// normal struct
pole lamp_pole;
cout<<"Check the size of rectangle = "<<sizeof(rectangle)<<" bytes"<<endl;
cout<<"Check the size of pole = "<<sizeof(pole)<<" bytes"<<endl<<endl;
cout<<"Using class instead of struct, using DEFAULT VALUE"<<endl;
cout<<"supplied by constructor, access through area() method"<<endl;
cout<<"----------------------------------------------------"<<endl<<endl;
cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl;
cout<<"Area of the square, square.area() = "<<square.area()<<endl<<endl;
// we can override the constructor values
wall.initialize(12, 10);
square.initialize(8,8);
cout<<"Using class instead of struct, USING ASSIGNED VALUE, access through area()
method"<<endl;
cout<<"---------------------------------------------------------------------------------"<<endl;
cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl;
cout<<"Area of the square, square.area()= "<<square.area()<<endl<<endl;
lamp_pole.length = 50;
lamp_pole.depth = 6;
cout<<"Just a comparison to the class, the following is a struct"<<endl;
cout<<"The length of the lamp pole is =
"<<lamp_pole.length*lamp_pole.depth<<endl<<endl;
} 52
Types of constructors
1. Default Constructor:-
• Default Constructor is also called as Empty
Constructor which has no arguments and It is
Automatically called when we creates the object of
class but Remember name of Constructor is same
as name of class and Constructor never declared
with the help of Return Type.
• Means we cant Declare a Constructor with the
help of void Return Type. , if we never Pass or
Declare any Arguments then this called as the
Copy Constructors.
53
Cont’d…
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Book{
private:
int pages;
char title[3];
public:
Book(int q, char w[3])
{
pages= q;
for(int i=0 ; i<3 ; i++)
{
title[i]= w[i];}
}
void show()
{
cout<<"Title:"<<title<<endl;
cout<<"Pages:"<<pages<<endl<<endl;}
};
main()
{
Book b1(25, "C++");
Book b2(b1);
Book b3= b1;
cout<<"detail of b1:"<<endl;
b1.show();
cout<<"detail of b2:"<<endl;
b2.show();
cout<<"detail of b3:"<<endl;
b3.show();
getch();
}
54
Cont’d…
2. Parameterized Constructor :-
• This is Another type Constructor which has some
Arguments and same name as class name but it
uses some Arguments So For this We have to
create object of Class by passing some Arguments
at the time of creating object with the name of
class.
• When we pass some Arguments to the Constructor
then this will automatically pass the Arguments to
the Constructor and the values will retrieve by the
Respective Data Members of the Class.
55
Cont’d…
3. Copy Constructor:-
• In this Constructor we pass the object of class into
the Another Object of Same Class.
• As name Suggests you Copy, means Copy the
values of one Object into the another Object of
Class .
• This is used for Copying the values of class object
into an another object of class So we call them as
Copy Constructor and For Copying the values We
have to pass the name of object whose values we
wants to Copying and When we are using or passing
an Object to a Constructor then we must have to
use the & Ampersand or Address Operator. 56
DESTRUCTOR
• The destructor of a class is a member function of a
class that is called automatically when an object of
the class goes out of scope.
• Among other things, this means that if an object of
the class type is a local variable for a function, then
the destructor is automatically called as the last
action before the function call ends.
• Destructors are used to eliminate any dynamically
allocated variables that have been created by the
object so that the memory occupied by these
dynamic variables is returned to the free store
manager for reuse. 57
Cont’d…
• Destructors may perform other clean-up tasks as
well. The name of a destructor must consist of the
tilde symbol, ~, followed by the name of the class.
58
Cont’d…
#include <iostream.h>
class CRectangle
{
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area ()
{
return (*width * *height);} };
CRectangle::CRectangle (int a, int b)
{ width = new int;
height = new int;
*width = a; *height = b; }
CRectangle::~CRectangle () {
delete width; delete height; }
int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0; }
#include<iostream.h>
#include<conio.h>
class test{
private:
int a;
public:
test()
{
cout<<"object is created :"<<endl<<endl;
}
~test()
{
cout<<"Object is destroyed"<<endl<<endl;}
};
main()
{
test *p1= new test;
test *p2= new test;
delete p1;
delete p2;
getch();
}
59
Constructors VS destructors
• For global objects, an object’s constructor is called
once, when the program first begins execution.
• For local objects, the constructor is called each time the
declaration statement is executed.
• Local objects are destroyed when they go out of scope.
• Global objects are destroyed when the program ends.
• Constructors and destructors are typically declared as
public.
• That is why the compiler can call them when an object
of a class is declared anywhere in the program.
• If the constructor or destructor function is declared as
private then no object of that class can be created
outside of that class.
• A class can have multiple constructors.
• It is possible to pass arguments to a constructor
function.
• Destructor functions cannot have parameters. 60
Scope Resolution Operator (::)
• The scope resolution operator : : is a special
operator that allows access to a global variable that is hidden by a local
variable with the same name.
• is used to define a function outside a class or when
we want to use a global variable but also has a local
variable with same name
• To understand the concept of scope resolution
operator, consider this example.
61
Cont’d…
#include<iostream.h>
int x = 5;
int main ()
{
int x = 3;
cout<<”The local variable of outer block is: “<<X;
cout<<”nThe global variable is: “<<::X;
{
int x = 10;
cout <<”The local variable of inner block is: “<<X;
cout <<”n The global variable is: “<<::X;
}
return 0;
}
62
Cont’d…
#include<iostream.h>
int n=12; //global variable
int main()
{
int n=13; //local variable
cout<<::n<<endl; //print global variable:12
cout<<n<<endl; //print the local variable:13
}
63
Static members of class
• We can define class members static
using static keyword. When we declare a member
of a class as static it means no matter how many
objects of the class are created, there is only one
copy of the static member.
• A static member is shared by all objects of the class.
All static data is initialized to zero when the first
object is created, if no other initialization is present.
• We can't put it in the class definition but it can be
initialized outside the class as done in the following
example by redeclaring the static variable, using the
scope resolution operator :: to identify which class
it belongs to. 64
Cont’d…
#include <iostream.h>
class Box {
public:
static int objectCount; // Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l; breadth = b; height = h; // Increase every time object is created
objectCount++; }
double Volume() { return length * breadth * height; }
private: double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box };
// Initialize static member of class Box int
Box::objectCount = 0; int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0; } 65
Static Function Members:
• By declaring a function member as static, you make it
independent of any particular object of the class. A
static member function can be called even if no objects
of the class exist and the static functions are accessed
using only the class name and the scope resolution
operator ::.
• A static member function can only access static data
member, other static member functions and any other
functions from outside the class.
• Static member functions have a class scope and they do
not have access to the this pointer of the class. You
could use a static member function to determine
whether some objects of the class have been created
or not. 66
Cont’d…
#include <iostream>
class Box {
public:
static int objectCount; // Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0) {
cout <<"Constructor called." << endl;
length = l; breadth = b; height = h;
// Increase every time object is created
objectCount++;
} double Volume() { return length * breadth * height;
} static int getCount() { return objectCount; }
private: double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box };
// Initialize static member of class Box int
Box::objectCount = 0;
int main(void) {
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0; }
67
Friend functions
• In principle, private and protected members of a
class cannot be accessed from outside the same
class in which they are declared. However, this rule
does not apply to "friends".
• Friends are functions or classes declared with
the friend keyword.
• A non-member function can access the private and
protected members of a class if it is declared
a friend of that class. That is done by including a
declaration of this external function within the
class, and preceding it with the keyword friend:
68
Cont’d…
// friend functions
#include <iostream>
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) :
width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate (const Rectangle& param) {
Rectangle res; res.width = param.width*2;
res.height = param.height*2;
return res; }
int main () {
Rectangle foo;
Rectangle bar (2,3); foo = duplicate (bar);
cout << foo.area() << 'n';
return 0; } 69
Friend classes in C++:-
• These are the special type of classes whose all of the
member functions are allowed to access the private
and protected data members of a particular class is
known as friend class.
• Normally private and protected members could not be
accessed from outside the class but in some situations
the program has to access them in order to produce
the desired results.
• In such situations the friend classes are used, the use
of friend classes allows a class to access these members
of another class.
• The syntax of declaring a friend class is not very tough,
simply if a class is declared in another class with a
friend keyword it will become the friend of this class70
Cont’d…
#include<iostream.h>
#include<conio.h>
class A
{
private:
int a,b;
public:
A()
{
a=10;
b=20;
}
friend class B;
};
class B
{
public:
B()
void showA(A obj)
{
cout<<”The value of a: ”<<obj.a<<endl;
}
void showB(A obj)
{
cout<<”The value of b: ”<<obj.b<<endl;
}
};
main()
{
A x;
B y;
y.showA(x);
y.showB(x);
getch();
}
71
72

Contenu connexe

Similaire à CHAPTER -4-class and structure.pptx

Similaire à CHAPTER -4-class and structure.pptx (20)

Ch7 structures
Ch7 structuresCh7 structures
Ch7 structures
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Structures
StructuresStructures
Structures
 
Lab 13
Lab 13Lab 13
Lab 13
 
Structures
StructuresStructures
Structures
 
Structures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptxStructures_Final_KLE (2).pptx
Structures_Final_KLE (2).pptx
 
Structure
StructureStructure
Structure
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
 
Struct
StructStruct
Struct
 
Structures
StructuresStructures
Structures
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
1. structure
1. structure1. structure
1. structure
 
Structure in C
Structure in CStructure in C
Structure in C
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
lec14.pdf
lec14.pdflec14.pdf
lec14.pdf
 

Dernier

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 

Dernier (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 

CHAPTER -4-class and structure.pptx

  • 1. CHAPTER -4 Structure and Class After covering this unit you will understand… • Structures – Structure types – Structures initialization – Initializing structures • Classes – Defining, member functions – Public and private members – Accessor and mutator functions – Structures vs. classes 1
  • 2. Structure • A Structure is a collection of related data items, possibly of different types. • A structure type in C++ is called struct. • A struct is heterogeneous in that it can be composed of data of different types. • In contrast, array is homogeneous since it can contain only data of the same type. • Structures hold data that belong together. • Examples: – Student record: student id, name, major, gender, start year, … – Bank account: account number, name, currency, balance, … – Address book: name, address, telephone number, … • In database applications, structures are called records(columns). 2
  • 3. Structure • Individual components of a struct type are called members (or fields). • Members can be of different types (simple, array or struct). • A struct is named as a whole while individual members are named using field identifiers. • Complex data structures can be formed by defining arrays of structs. • A structure is collection of variables and methods 3
  • 4. structure • Before a structure can be used, it must be declared. Here is the general format of a structure declaration: struct tag { variable declaration; // ... more declarations //may follow... }; • The tag is the name of the structure. it’s used like a data type name. • The variable declarations that appear inside the braces declare members of the structure. 4
  • 5. Declaring structure • struct keyword is used for declaration • In a structure, variables can have different data types • Can have private, protected and public access specifiers • The default access specifier is public • Semicolon “;” comes in the end to complete structure declaration 5
  • 6. Cont’d… struct Student{ char name; int batch int Id; int age; char sex; double CGA; }; struct Date { int day; int month; int year; } ; The “Student” structure has 6 members of different types. While in database , struct name student is termed as”main database table name” and the variables listed are said to be “records” with the same data types The “Date” structure has 3 members, day, month & year. 6
  • 7. Cont’d… struct employee { string firstName; string lastName; string address1; string address2; double salary; string deptID; }; defines a struct employee with six members. The members firstName, lastName, address1, address2, and deptID are of type string, and the member salary is of type double. Like any type definition, a struct is a definition, not a declaration. That is, it defines only a data type; no memory is allocated. 7
  • 8. Accessing struct Members • In arrays, you access a element by using the array name together with the relative position (index) of the component. The array name and index are separated using square brackets. • To access a structure member (component), you use the struct variable name together with the member name; these names are separated by a dot (period). The syntax for accessing a struct member is: structVariableName.memberName 8
  • 9. .dot operator • C++ provides the dot operator (a period) to access the individual members of a structure. • the following statement demonstrates how to access the salary member: Employee.salary = 475; • In this statement, the number 475 is assigned to the salary member of employee. • The dot operator connects the name of the member variable with the name of the structure variable it belongs to. 9
  • 10. Cont’d… • The following statements assign values to the empNumber members of the deptHead, foreman, and associate structure variables: deptHead.empNumber = 78; foreman.empNumber = 897; associate.empNumber = 729; 10
  • 11. Cont’d… • With the dot operator you can use member variables just like regular variables. • For example these statements display the contents of deptHead’s members: cout << deptHead.empNumber << endl; cout << deptHead.name << endl; cout << deptHead.hours << endl; cout << deptHead.payRate << endl; cout << deptHead.grossPay << endl; 11
  • 12. Cont’d… #include<iostream.h> struct telephone { char *name; int number; }; int main() { struct telephone index; index.name = "Jane Monroe"; index.number = 12345; cout << "Name: " << index.name << 'n'; cout << "Telephone number: " << index.number; return 0; } 12
  • 13. Initializing a Structure • The members of a structure variable may be initialized with starting values when the structure variable is declared. struct GeoInfo { char cityName[30]; char state[3]; long population; int distance; }; GeoInfo location = {“Ashville”, “NC”, 50000, 28}; 13
  • 14. Struct example #include<iostream.h> struct Date { int month; int day; int year; }; void main() { //Date dueDate; Date dueDate = {12, 31, 2003}; cout<< dueDate.month <<endl; cout<< dueDate.day <<endl; cout<< dueDate.year << endl; } 14
  • 15. Cont’d… #include <iostream.h> struct PayRoll { int empNumber; // Employee number char name[25]; // Employee's name float hours; // Hours worked float payRate; // Hourly Payrate float grossPay; // Gross Pay }; void main(void) { PayRoll employee;/*Employee is a PayRoll structure or employee is a structure variable name and empnumber---gross pay are calledmembers of the structure called payroll */ cout << "Enter the employee's number: "; cin >> employee.empNumber; cout << "Enter the employee's name: "; cin.ignore(); // To skip the remaining 'n' character cin.getline(employee.name, 25); cout << "How many hours did the employee work? "; cin >> employee.hours; cout << "What is the employee's hourly payrate? "; cin >> employee.payRate; employee.grossPay = employee.hours * employee.payRate; cout << "Here is the employee's payroll data:n"; cout << "Name: " << employee.name << endl; cout << "Number: " << employee.empNumber << endl; cout << "Hours worked: " << employee.hours << endl; cout << "Hourly Payrate: " << employee.payRate << endl; cout << "Gross Pay: $" << employee.grossPay << endl; } 15
  • 16. Struct example #include <iostream.h> #include <math.h> // For the pow function? #include <iomanip.h> // Constant for pi. const double PI = 3.14159; // Structure declaration struct Circle { double radius; // A circle's radius double diameter; // A circle's diameter double area; // A circle's area }; int main() { Circle c; // Define a structure variable; circle =structure name;c = struct variable name // Get the circle's diameter. cout << "Enter the diameter of a circle: "; cin >> c.diameter; // Calculate the circle's radius. c.radius = c.diameter / 2; // Calculate the circle's area. c.area = PI * pow(c.radius, 2.0); // Display the circle data. //cout << fixed << showpoint << setprecision(2); cout << "The radius and area of the circle are:n"; cout << "Radius: " << c.radius << endl; cout << "Area: " << c.area << endl; return 0; } 16
  • 17. Assignment in struct • We can assign the value of one struct variable to another struct variable of the same type by using an assignment statement. 17
  • 18. Cont’d.. The statement: student = newStudent; • copies the contents of newStudent into student. 18
  • 19. Cont’d… In fact, the assignment statement: student = newStudent; is equivalent to the following statements: student.firstName = newStudent.firstName; student.lastName = newStudent.lastName; student.courseGrade = newStudent.courseGrade; student.testScore = newStudent.testScore; student.programmingScore = newStudent.programmingScore; student.GPA = newStudent.GPA; 19
  • 20. Cont’d… #include <iostream.h> #include <iomanip.h> struct student { char st_name[25]; char grade; int age; float average; }; void main() { student std1 = {"Joe Brown", 'A', 13, 91.488888}; struct student std2, std3; // Not initialized std2 = std1; // Copies each member of std1 std3 = std1; // to std2 and std3. cout << "The contents of std2:n"; cout << std2.st_name << " " << std2.grade <<" "; cout << std2.age << " " << std2.average << "nn"; cout << "The contents of std3:n"; cout << std3.st_name << " " << std3.grade << " "; cout << std3.age << " " << std3.average << "n"; return; } 20
  • 21. Nested Structures • C++ gives you the ability to nest one structure definition in another. • You have to define the common members only once in their own structure and then use that structure as a member in another structure. • Nesting of structures is placing structures within structure. 21
  • 22. Cont’d… • When a structure is declared as the member of another structure, it is called Structure within a structure. It is also known as nested structure. Example of nested structure One example of nested structure is given below: struct date { // members of structure int day; int month; int year; }; struct company { char name[20]; long int employee_id; char sex[5]; int age; struct date dob;}; 22
  • 23. Cont’d… #include<iostream.h> #include<string.h> #define MAX 1000 // structure block defination struct date{ // members of structure definition int day; int month; int year; }; struct company{ char name[20]; long int employee_id; char sex[5]; int age; // nested block defination struct date dob; }; // structuer object defination company employee[MAX]; // main function starts int main(){ company employee[MAX]; int n; cout << "A program for collecting employee information"; cout << endl; cout << "And displaying the collected information"; cout << endl << endl; cout << "How many employees:"; cin >> n; cout << endl; // functions defination void CollectInformtion(company employee[MAX], int n); void Display(company employee[MAX], int n); // functions calling CollectInformtion(employee, n); Display(employee, n); cin.get(); return 0; } // collecting information form the user void CollectInformtion(company employee[MAX], int n){ cout << "Enter the following information:"; cout << endl << endl; for (int i=1; i<=n; i++){ cout << "Enter information for employee no: " << i; cout << endl; cout << "Name :"; cin >> employee[i].name; cout << "ID :"; cin >> employee[i].employee_id; cout << "Sex :"; cin >> employee[i].sex; cout << "Age :"; cin >> employee[i].age; cout << "Date of Birth:" << endl; cout << "Day :"; cin >> employee[i].dob.day; cout << "Month :"; cin >> employee[i].dob.month; cout << "Year :"; cin >> employee[i].dob.year; cout << endl; } } // displaying entered information to the standard output void Display(company employee[MAX], int n){ cout << "Employee entered information:"; cout << endl; cout << "Name ID Sex Age Date of Birth" << endl; for (int i=1; i<=n; i++){ cout << employee[i].name << "t"; cout << employee[i].employee_id << "t"; cout << employee[i].sex; cout << "t"; cout << employee[i].age; cout << "t"; cout << employee[i].dob.day << "."; cout << employee[i].dob.month << "."; cout << employee[i].dob.year ; cout << endl; } } 23
  • 24. Cont’d… #include <iostream.h> struct Date { int month; int day; int year; }; struct Place { char address[50]; char city[20]; char state[15]; char zip[11]; }; struct EmpInfo { char name[50]; int empNumber; Date birthDate; Place residence; }; void main(void) { EmpInfo manager; // Ask for the manager's name and employee number cout << "Enter the manager's name: "; cin.getline(manager.name, 50); cout << "Enter the manager's employee number: "; cin >> manager.empNumber; 24
  • 25. Cont’d… // Get the manager's birth date cout << "Now enter the manager's date-of-birth.n"; cout << "Month (up to 2 digits): "; cin >> manager.birthDate.month; cout << "Day (up to 2 digits): "; cin >> manager.birthDate.day; cout << "Year (2 digits): "; cin >> manager.birthDate.year; cin.get(); // Eat the remaining newline character // Get the manager's residence information cout << "Enter the manager's street address: "; cin.getline(manager.residence.address, 50); cout << "City: "; cin.getline(manager.residence.city, 20); cout << "State: "; cin.getline(manager.residence.state, 15); cout << "Zip Code: "; cin.getline(manager.residence.zip, 11); // Display the information just entered cout << "nHere is the manager's information:n"; cout << manager.name << endl; cout << "Employee number " << manager.empNumber << endl; cout << "Date of Birth: "; cout << manager.birthDate.month << "-"; cout << manager.birthDate.day << "-"; cout << manager.birthDate.year << endl; cout << "Place of residence:n"; cout << manager.residence.address << endl; cout << manager.residence.city << ", "; cout << manager.residence.state << " "; cout << manager.residence.zip << endl; } 25
  • 26. Strings as Structure Members When a character array is a structure member, use the same sting manipulation techniques with it as you would with any other character array. 26
  • 27. Cont’d… #include <iostream.h> #include <string.h> struct Name { char first[15]; char middle[15]; char last[15]; char full[45]; }; void main(void) { Name person; cout << "Enter your first name: "; cin >> person.first; cout << "Enter your middle name: "; cin >> person.middle; cout << "Enter your last name: "; cin >> person.last; strcpy(person.full, person.first); strcat(person.full, " "); strcat(person.full, person.middle); strcat(person.full, " "); strcat(person.full, person.last); cout << "nYour full name is " << person.full << endl; } 27
  • 28. Arrays of Structures • Arrays of structures can simplify some programming tasks. struct BookInfo { char title[50]; char author[30]; char publisher[25]; float price; }; BookInfo bookList[20]; 28
  • 29. class • Class is a collection of data member and member function. Objects are also called instance of the class. • A class is similar to a structure. It is a data type defined by the programmer, consisting of variables and functions. • Each object contains all members(variables and functions) declared in the class. • We can access any data member or member function from object of that class using . • A class is the collection of related data and function under a single name. • A C++ program can have any number of classes. When related data and functions are kept under a class, it helps to visualize the complex problem efficiently and effectively. 29
  • 30. A Class is a blueprint for objects When a class is defined, No Memory Is Allocated. You can imagine like a data type. int var; The above code specifies var is a variable of type integer; int is used for specifying variable var is of integer type. Similarly, class are also just the specification for objects and object bears the property of that class. A class specification has two parts : 1) Class declaration 2) Class Function Definitions 30
  • 31. Cont’d… A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; 31
  • 32. class • The keyword public determines the access attributes of the members of the class that follow it. • A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected . 32
  • 33. Define C++ Objects: • A class provides the blueprints(sth acts as template for sth) for objects, so basically an object is created from a class. • We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box: Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box 33
  • 34. Accessing the Data Members: The public data members of objects of a class can be accessed using the direct member access operator (.). 34
  • 35. Cont’d… #include <iostream> class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0; // volume of box 1 volume = Box1.height * Box1.length * Box1.breadth; cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.height * Box2.length * Box2.breadth; cout << "Volume of Box2 : " << volume <<endl; return 0; } 35
  • 36. Access Specifiers • C++ provides the key words private and public which you may use in class declarations. • These key words are known as access specifiers because they specify how class members may be accessed. The following is the general format of a class declaration that uses the private and public access specifiers. class ClassName { private: // Declarations of private // members appear here. public: // Declarations of public // members appear here. }; 36
  • 38. Cont’d… • The keyword class specifies user defined data type class name • The body of a class is enclosed within braces and is terminated by a semicolon • The class body contains the declaration of variables and functions • The class body has three access specifiers ( visibility labels) viz., private , public and protected • Specifying private visibility label is optional. By default the members will be treated as private if a visibility label is not mentioned • The members that have been declared as private, can be accessed only from within the class • The members that have been declared as protected can be accessed from within the class, and the members of the inherited classes. • The members that have been declared as public can be accessed from outside the class also 38
  • 39. Data Abstraction • The binding of data and functions together into a single entity is referred to as encapsulation. • The members and functions declared under private are not accessible by members outside the class, this is referred to as data hiding. • Instruments allowing only selected access of components to objects and to members of other classes is called as Data Abstraction. Or rather Data abstraction is achieved through data hiding. 39
  • 40. Data Members and Member Functions • Class comprises of members. Members are further classified as Data Members and Member functions. Data members are the data variables that represent the features or properties of a class. • Member functions are the functions that perform specific tasks in a class. • Member functions are called as methods, and data members are also called as attributes. 40
  • 42. Accessors and Mutators • A member function that gets a value from a class’s member variable but does not change it is known as an accessor. • A member function that stores a value in member variable or changes(mutates) the value of member variable in some other way is known as a mutator. • In the Rectangle class, the member functions getLength and getWidth are accessors, and the member functions setLength and setWidth are mutators. • Some programmers refer to mutators as setter functions because they set the value of an attribute, and accessors as getter functions because they get the value of an attribute. 42
  • 43. Cont’d… #include <iostream> class Rectangle { int width, height; public: void set values(int,int); //mutator int area () { return width*height;} }; void Rectangle::set_values (int x, int y) { width = x; height = y; } int main () { Rectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } 43
  • 44. Creating Objects • declaration statement student stud; This statement may be read as stud is an instance or object of the class student. Syntax for object declaration. • Once a class has been declared, variables of that type can be declared. ‘stud’ is a variable of type student ,student is a data type of class . • In C++ the class variables are known as objects. The declaration of an object is similar to that of a variable of any basic type. • Objects can also be created by placing their names immediately after the closing brace of the class declaration. 44
  • 45. Cont’d… • Class objects must be defined after the class is declared. Rectangle box; • ClassName is the name of a class and objectName is the name we are giving the object. • Defining a class object is called the instantiation of a class. In this statement, box is an instance of the Rectangle class. 45
  • 46. Accessing an Object’s Members • The members of a class are accessed using the dot operator. • The dot operator is used to connect the object and the member function. • For example, the call statement to the function execute() of the class student may be given as: box.setWidth(12.7); 46
  • 47. Defining methods of a class/member functions/ 47
  • 48. Cont’d… • In Method 1, the member function add() is declared and defined within class add. • In Method 2, the member function display() is declared within the class, and defined outside the class. • The member function have some special characteristics that are often used in the program development . • Several different classes can use the same function name. The ‘membership’ label will resolve their scope Member functions can access the private data of a class. A nonmember function cannot do so. • A member function can call another member function directly, without using the dot operator. ( This is called as nesting of member functions ) • The member functions can receive arguments of a valid C++ data type. Objects can also be passed as arguments • The return type of a member function can be of object data type Member functions can be of static type 48
  • 49. constructor • A constructor is a member function that is automatically called when an object of that class is declared. • A constructor is used to initialize the values of some or all member variables and to do any other sort of initialization that may be needed. • A constructor is a member function of a class that has the same name as the class. • A constructor is called automatically when an object of the class is declared. Constructors are used to initialize objects. • A constructor must have the same name as the class of which it is a member. 49
  • 50. CONSTRUCTOR DEFINITIONS You define a constructor the same way that you define any other member function, except for two points: 1. A constructor must have the same name as the class. For example, if the class is named BankAccount , then any constructor for this class must be named BankAccount 2. A constructor definition cannot return a value. Moreover, no type, not even Void can be given at the start of the function declaration or in the function header. Constructors can be overloaded 50
  • 51. Cont’d… class rectangle { // A simple class int height; int width; public: rectangle(void); // with a constuctor, ~rectangle(void); // and a destructor }; rectangle::rectangle(void) // constuctor { height = 6; width = 6; } 51
  • 52. Cont’d… #include <iostream.h> // A simple class declaration class rectangle { // private access by default, access only through the method or interface int height; int width; // public public: // constructor, initial object construction, allocating storage, initial value etc. rectangle(void); // methods, access something, do something int area(void); void initialize(int, int); // destructor, destroy all the object, return resources such as memory etc. to the system ~rectangle(void); }; // class implementation // constructor implementation rectangle::rectangle(void) { // give initial values height = 6; width = 6; } int rectangle::area(void) { // just return the area return (height * width); } void rectangle::initialize(int initial_height, int initial_width) { // give initial values height = initial_height; width = initial_width; } // destructor implementation rectangle::~rectangle(void) { // destroy all the object an return the resources to the system height = 0; width = 0; } // normal structure - compare with class usage struct pole { int length; int depth; }; // comes the main() void main(void) { // class object instantiations rectangle wall, square; // normal struct pole lamp_pole; cout<<"Check the size of rectangle = "<<sizeof(rectangle)<<" bytes"<<endl; cout<<"Check the size of pole = "<<sizeof(pole)<<" bytes"<<endl<<endl; cout<<"Using class instead of struct, using DEFAULT VALUE"<<endl; cout<<"supplied by constructor, access through area() method"<<endl; cout<<"----------------------------------------------------"<<endl<<endl; cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl; cout<<"Area of the square, square.area() = "<<square.area()<<endl<<endl; // we can override the constructor values wall.initialize(12, 10); square.initialize(8,8); cout<<"Using class instead of struct, USING ASSIGNED VALUE, access through area() method"<<endl; cout<<"---------------------------------------------------------------------------------"<<endl; cout<<"Area of the wall, wall.area() = "<<wall.area()<<endl; cout<<"Area of the square, square.area()= "<<square.area()<<endl<<endl; lamp_pole.length = 50; lamp_pole.depth = 6; cout<<"Just a comparison to the class, the following is a struct"<<endl; cout<<"The length of the lamp pole is = "<<lamp_pole.length*lamp_pole.depth<<endl<<endl; } 52
  • 53. Types of constructors 1. Default Constructor:- • Default Constructor is also called as Empty Constructor which has no arguments and It is Automatically called when we creates the object of class but Remember name of Constructor is same as name of class and Constructor never declared with the help of Return Type. • Means we cant Declare a Constructor with the help of void Return Type. , if we never Pass or Declare any Arguments then this called as the Copy Constructors. 53
  • 54. Cont’d… #include<iostream.h> #include<conio.h> #include<string.h> class Book{ private: int pages; char title[3]; public: Book(int q, char w[3]) { pages= q; for(int i=0 ; i<3 ; i++) { title[i]= w[i];} } void show() { cout<<"Title:"<<title<<endl; cout<<"Pages:"<<pages<<endl<<endl;} }; main() { Book b1(25, "C++"); Book b2(b1); Book b3= b1; cout<<"detail of b1:"<<endl; b1.show(); cout<<"detail of b2:"<<endl; b2.show(); cout<<"detail of b3:"<<endl; b3.show(); getch(); } 54
  • 55. Cont’d… 2. Parameterized Constructor :- • This is Another type Constructor which has some Arguments and same name as class name but it uses some Arguments So For this We have to create object of Class by passing some Arguments at the time of creating object with the name of class. • When we pass some Arguments to the Constructor then this will automatically pass the Arguments to the Constructor and the values will retrieve by the Respective Data Members of the Class. 55
  • 56. Cont’d… 3. Copy Constructor:- • In this Constructor we pass the object of class into the Another Object of Same Class. • As name Suggests you Copy, means Copy the values of one Object into the another Object of Class . • This is used for Copying the values of class object into an another object of class So we call them as Copy Constructor and For Copying the values We have to pass the name of object whose values we wants to Copying and When we are using or passing an Object to a Constructor then we must have to use the & Ampersand or Address Operator. 56
  • 57. DESTRUCTOR • The destructor of a class is a member function of a class that is called automatically when an object of the class goes out of scope. • Among other things, this means that if an object of the class type is a local variable for a function, then the destructor is automatically called as the last action before the function call ends. • Destructors are used to eliminate any dynamically allocated variables that have been created by the object so that the memory occupied by these dynamic variables is returned to the free store manager for reuse. 57
  • 58. Cont’d… • Destructors may perform other clean-up tasks as well. The name of a destructor must consist of the tilde symbol, ~, followed by the name of the class. 58
  • 59. Cont’d… #include <iostream.h> class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () { return (*width * *height);} }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } #include<iostream.h> #include<conio.h> class test{ private: int a; public: test() { cout<<"object is created :"<<endl<<endl; } ~test() { cout<<"Object is destroyed"<<endl<<endl;} }; main() { test *p1= new test; test *p2= new test; delete p1; delete p2; getch(); } 59
  • 60. Constructors VS destructors • For global objects, an object’s constructor is called once, when the program first begins execution. • For local objects, the constructor is called each time the declaration statement is executed. • Local objects are destroyed when they go out of scope. • Global objects are destroyed when the program ends. • Constructors and destructors are typically declared as public. • That is why the compiler can call them when an object of a class is declared anywhere in the program. • If the constructor or destructor function is declared as private then no object of that class can be created outside of that class. • A class can have multiple constructors. • It is possible to pass arguments to a constructor function. • Destructor functions cannot have parameters. 60
  • 61. Scope Resolution Operator (::) • The scope resolution operator : : is a special operator that allows access to a global variable that is hidden by a local variable with the same name. • is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name • To understand the concept of scope resolution operator, consider this example. 61
  • 62. Cont’d… #include<iostream.h> int x = 5; int main () { int x = 3; cout<<”The local variable of outer block is: “<<X; cout<<”nThe global variable is: “<<::X; { int x = 10; cout <<”The local variable of inner block is: “<<X; cout <<”n The global variable is: “<<::X; } return 0; } 62
  • 63. Cont’d… #include<iostream.h> int n=12; //global variable int main() { int n=13; //local variable cout<<::n<<endl; //print global variable:12 cout<<n<<endl; //print the local variable:13 } 63
  • 64. Static members of class • We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. • A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. • We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to. 64
  • 65. Cont’d… #include <iostream.h> class Box { public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl; return 0; } 65
  • 66. Static Function Members: • By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. • A static member function can only access static data member, other static member functions and any other functions from outside the class. • Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not. 66
  • 67. Cont’d… #include <iostream> class Box { public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } static int getCount() { return objectCount; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { // Print total number of objects before creating object. cout << "Inital Stage Count: " << Box::getCount() << endl; Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects after creating object. cout << "Final Stage Count: " << Box::getCount() << endl; return 0; } 67
  • 68. Friend functions • In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to "friends". • Friends are functions or classes declared with the friend keyword. • A non-member function can access the private and protected members of a class if it is declared a friend of that class. That is done by including a declaration of this external function within the class, and preceding it with the keyword friend: 68
  • 69. Cont’d… // friend functions #include <iostream> class Rectangle { int width, height; public: Rectangle() {} Rectangle (int x, int y) : width(x), height(y) {} int area() {return width * height;} friend Rectangle duplicate (const Rectangle&); }; Rectangle duplicate (const Rectangle& param) { Rectangle res; res.width = param.width*2; res.height = param.height*2; return res; } int main () { Rectangle foo; Rectangle bar (2,3); foo = duplicate (bar); cout << foo.area() << 'n'; return 0; } 69
  • 70. Friend classes in C++:- • These are the special type of classes whose all of the member functions are allowed to access the private and protected data members of a particular class is known as friend class. • Normally private and protected members could not be accessed from outside the class but in some situations the program has to access them in order to produce the desired results. • In such situations the friend classes are used, the use of friend classes allows a class to access these members of another class. • The syntax of declaring a friend class is not very tough, simply if a class is declared in another class with a friend keyword it will become the friend of this class70
  • 71. Cont’d… #include<iostream.h> #include<conio.h> class A { private: int a,b; public: A() { a=10; b=20; } friend class B; }; class B { public: B() void showA(A obj) { cout<<”The value of a: ”<<obj.a<<endl; } void showB(A obj) { cout<<”The value of b: ”<<obj.b<<endl; } }; main() { A x; B y; y.showA(x); y.showB(x); getch(); } 71
  • 72. 72