MODULE 3
Classes and Data Abstraction
Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional.
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −
#include <iostream>
#include <cstring>
using namespace std;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info
cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;
// Print Book2 info
cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
Introduction to Class
class Book
Structure of a class
Class |
Data Members |
Member functions |
Structure of a “Book” class
Book |
Data Members name pages price |
Member functions Accept() Display() |
Structure of class declaration
class class_name
{
Access specifier:
Data Members;
Access specifier:
Member Functions;
};
We will discuss new terms in above declaration.
Class
Access Specifier
It specifies if class members are accessible to external functions (functions of other classes).
C++ provides three access specifiers :
Fig. C3.2 : Types of access specifiers
1. private
2. public
3. protected
class A
{
friend class B;
};
Write a program to calculate area of cube and triangle using friend class
Solution :
#include <iostream>
using namespace std;
class cube; // Step 1 forward declaration
class Triangle {
int x,y;
public:
Triangle(int a,int b) // constructor
{
x=a;
y=b;
}
void display()
{
cout << "Area of triangle is " << ½*x*y << endl;
}
void area(cube &); // Step 2
};
class cube{
int s;
public:
cube(int p )
{
s=p;
}
void show()
{
cout << "Volume of cube is: " << s*s*s << endl;
}
friend class triangle; //Step 3 triangle is friend of class cube
};
void triangle::area(cube &p)
{
x = p.s; //Step 4
y = p.s;
}
int main () {
triangle T(10,5);
cube C(10);
T.display();
C.show();
T.area(C);
T.display();
C.show();
return 0;
}
Output
Area of triangle is 25
Volume of cube is 1000
Area of triangle is 50
Volume of cube is 1000
Operation | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | <<>> | Left to right |
Relational | << =>>= | Left to right |
Equality | ==!= | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ? | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
When the scope of a declaration extends to or past the end of a class definition, the regions defined by the member definitions of that class are included in the scope of the class. Members defined lexically outside of the class are also in this scope. In addition, the scope of the declaration includes any portion of the declarator following the identifier in the member definitions.
The name of a class member has class scope and can only be used in the following cases:
In a member function of that class
In a member function of a class derived from that class
After the . (dot) operator applied to an instance of that class
After the . (dot) operator applied to an instance of a class derived from that class, as long as the derived class does not hide the name
After the -> (arrow) operator applied to a pointer to an instance of that class
After the -> (arrow) operator applied to a pointer to an instance of a class derived from that class, as long as the derived class does not hide the name
After the :: (scope resolution) operator applied to the name of a class
After the :: (scope resolution) operator applied to a class derived from that class
// creates object b1 of class Book
Object
b1 |
Data Members: name pages price |
Member functions: Accept() Display() |
b1 |
| b2 |
Data Members : name pages price |
| Data Members : name pages price |
Member functions: Accept() Display() |
| Member functions : Accept() Display() |
Fig: Classes and objects
Write a program to accept and display details of book.
Solution :
#include<iostream> //Step 1 Header file
using namespace std ;
class Book //Step 2 Declares class Book
{
char name[10]; // Declares data members name,
// pages and price.
int pages; // These data members are private.
float price;
public: //Starts public section of class book
void accept() //Step 3 Defines function “accept”
{ //Entering the details of book
cout<<“Enter name of book”;
cin>>name;
cout<<“Enter pages of book”;
cin>>pages;
cout<<“Enter price of book”;
cin>>price;
} //End of accept function definition
void display() //Step 4 Defines function display
{ // Displays all the details of book
cout<<“Name of book is :”<<name;
cout<<“No. of Pages in book are :”<<pages;
cout<<“Price of book is:”<<price;
} // End of display function
}; //Step 5 End of class
int main() //Step 6 Start of main() function
{
Book b1,b2; //Step 7 Creates objects b1,b2
b1.accept(); //Step 8 Calls accept function for b1
b2.accept(); // Calls accept function for b2
b1.display(); //Step 9 Calls display function for b1
b2.display(); //Calls display function for b2
return 0;
} // End of main
Explanation
Step 1 : Every C++ program starts with header file “iostream.h” as it contains declarations of input and output streams in program.
#include<iostream>
using namespace std ;
Step 2 : Class “Book” is declared and defined. It consists of data members name, pages and price. Access specifier is not mentioned for these members so they are considered as private.
class Book //Declares class Book
{
char name[10];
//Declares data members name, pages and price. These int pages; data members are private.
float price;
Step 3 : Accept function accepts all the details of book. It shows new features cout, <<, cin, >>.
cout
Standard predefined object that represents standard output stream in C++.
<<: Insertion or output operator
cout<< name<<“ ”<< pages<<“ ”<< price; // Separating output by space
cout<<name<<“,”<< pages<<“,”<< price; // Separating output by comma
cin
Standard predefined object that represents standard input stream in C++.
>>:Extraction or input operator
void accept() //Defines function “accept”
{ //Entering the details of book
cout<<“Enter name of book”;
cin>>name;
cout<<“Enter pages of book”;
cin>>pages;
cout<<“Enter price of book”;
cin>>price;
} //End of accept function definition
Step 4: Defines display function.
It displays all the details of book.
void display() // Defines function display
{ // Displays all the details of book
cout<<“Name of book is :”<<name;
cout<<“No. of Pages in book are :”<<pages;
cout<<“Price of book is:”<<price;
} // End of display function
Step 5: It indicates end of class definition.
}; // End of class
Step 6: In C++ main is always written outside class.
int main() // Start of main() function
Step7: Two objects of class book b1 and b2 are created.
Book b1,b2; // Creates objects b1,b2
Step 8: In main() every function is called with object and dot operator.
Syntax for function call from main()
objectname.functionname(arguments);
eg. obj1.accept();
Using b1.accept() we are accepting data for object b1.
Similarly b2.accept will accept data for object b2.
b1.accept(); //Calls accept function for b1
b2.accept(); // Calls accept function for b2
Step 9: b1.display() will print details of book b1.
Similarly b2.display() prints details of book b2.
b1.display(); // Calls display function for b1
b2.display(); //Calls display function for b2
Step 10: End of main indicates end of program.
} // End of main
returntype functionname(argument list)
{
Function Definition
}
eg. void display()
{
cout<<name<<pages<<price;
}
returntype classname :: functionname(argument list)
{
Function Definition
}
Example
void Book :: display()
{
cout<<name<<pages<<price;
}
Program
Write a C++ program to find if a number is even or odd using scope resolution operator.
Solution :
#include<iostream> using namespace std ; class Example { int number; public: void accept(); void EvenOdd(); }; void Example::accept() { cout<<“Enter number”; cin>>number; } void Example:: EvenOdd() { if(number%2= =0) cout<<number<<“is even number”; else cout<<number<<“is odd number”; } void main() { Example O; O.accept(); O.EvenOdd(); } | //Header file
//Declares class Example //Declares data member number. It is private data member. //Starts public section of class Example //Declares functions “accept” and EvenOdd
//End of class definition //Defining accept function outside class using scope resolution operator.
//Accepting value for number from user //End of accept function definition //Defining EvenOdd function outside class using scope resolution operator.
//Checks if number is even or odd
//End of EvenOddfunction //Start of main() function //Creates object O //Calls accept function //Calls EvenOdd function //End of main |
Accessor function.
Mutuator functions
Mutuator function does modification of protected data members
class example
{
int x,y;
public:
example() //constructor, same name as that of class
{
}
void display()
{
:
}
};
class example
{
int x,y;
public:
example() //constructor initializing data members of class
{
x=10;
y=20;
}
void display()
{
:
}
};
class example
{
private:
int x,y;
example() // error, constructor declared under private section
{
x=10;
y=20;
}
:
:
};
class example
{
int x, y;
public:
void example() // error, constructor does not have return type
{
x=10;
y=20;
}
:
:
};
class example
{
int x, y;
public:
example() // constructor
{
x=10;
y=20;
}
void display()
{
cout<<x<<y;
}
};
int main()
{
example obj; //invokes constructor and initialize data
member x and y to 10 and 20 respectively.
obj.display();
return 0 ;
}
class example
{
int x, y;
public:
example(); // constructor declared
:
:
};
example::example(); // constructor defined outside class
{
x=10;
y=20;
}
Types of constructors with syntax
Fig: Types of Constructor
Default /Non parameterized Constructor
class Volume
{
int x;
public:
Volume () // default constructor
{
x=10;
}
void display()
{
cout<<x*x*x;
}
};
void main()
{
Volume Obj; //invokes default constructor
Obj.display();
}
Parameterized Constructor
A constructor that receives parameters is parameterized constructor.
class Volume {
int x;
public:
Volume ( int a) // parameterized constructor
{
x=a;
}
void display()
{
cout<<x*x*x;
}
};
int main()
{
Volume obj(10); //invokes parameterized constructor
and pass argument 10 to it.
obj.display();
}
Copy Constructor
Copy constructor initializes an object using values of another object passed to it as a parameter.
class Volume
{
int x;
public:
Volume ( int & P) // copy constructor
{
x=P.x; //copies value
}
void display()
{
cout<<x*x*x;
}
};
int main()
{
Volume obj1; //invokes default constructor
Volume obj2(obj1); //calls copy constructor
obj2.display();
}
Constructors can be overloaded just like member functions. Thus we can have multiple constructors in a class.
Write a C++ program to find volume of cube, cylinder.
Solution :
#include<iostream>
using namespace std ;
class Volume //Defines class Volume
{
int x,y,z;
public:
Volume ( int a) // Step 1Constructor with one argument
{
x=a;
}
Volume ( int a, int b) // Step 2 Constructor with two arguments
{
x=a;
y=b;
}
void displaycube();
void displaycylinder();
};
void Volume::displaycube()
// Step 3 Function to calculate volume of cube
{
cout<<x*x*x;
}
void Volume::displaycylinder()
//Step 4 Function to calculate volume of cylinder
{
cout<<3.14*x*x*y;
}
int main()
{
Volume obj1(10);
// Step 5Calls constructor with one argument.
Volume obj2(10,5);
// Step 6 Calls constructor with two arguments.
obj1. displaycube (); //Step 7
obj2. displaycylinder ();
return 0 ;
}
Explanation
This program calculates volume of cube and cylinder. For this we use two constructors in a class. One constructor is to initialize data member for cube and other to initialize data members for cylinder.
Step 1 : Defines constructor with one argument. Here x stands for side of a cube.
Volume ( int a) { x=a; } | //Constructor with one argument
|
Step 2 : Defines constructor with two arguments. Here x and y specifies radius and height.
Volume ( int a, int b) { x=a; y=b; } | //Constructor with two arguments
|
Step 3 : Defines Function to calculate volume of cube.
void Volume::displaycube() { cout<<x*x*x; } | //Function to calculate volume of cube
|
Step 4 : Defines Function to calculate volume of cylinder
void Volume::displaycylinder() { cout<<3.14*x*x*y; } | //Function to calculate volume of cylinder
|
Step 5 : Here we want to initialize side of cube so we pass only one argument to invoke constructor with one argument.
Volume obj1(10); |
Step 6 : Here we want to initialize radius and height of cylinder so we pass two arguments to invoke constructor with two arguments.
Volume obj2(10,5); |
Step 7 : Calls functions to calculate volume of a cube and cylinder.
obj1. displaycube (); obj2. displaycylinder (); |
Default /Non parameterized Constructor
class Volume
{
int x;
public:
Volume () // default constructor
{
x=10;
}
void display()
{
cout<<x*x*x;
}
};
void main()
{
Volume Obj; //invokes default constructor
Obj.display();
}
class example
{
public:
~example();//destructor
};
Reference Books
1. The C++ Programming language 3/e by Bjarne Stroustrup, Pearson Education.
2. C++, How to Programme, 4e, by Deitel, Pearson Education.
3. Big C++ by Cay Horstmann, Wiley India.
4. C++ Primer, 3e by Stanley B. Lippmann, JoseeLajoie, Pearson Education.
5. C++ and Object Oriented Programming Paradigm, 2e by Debasish Jana, PHI.
6. Programming with C++, 2/e by Ravichandran, Tata McGraw Hill.
7. C++ Programming Black Book by Steven Holzner, Dreamtech Press.