Professional Documents
Culture Documents
functions to set, display, get and input data. In main function, create 02 student
objects, input and display their data.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
void SetData(int r0, char *n0, int m0)
{
rollno = r0;
strcpy(name, n0);
marks = m0;
}
void DispData()
{
cout << "Rollno=" << rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
void InputData()
{
cout << "give rollno" << endl;
cin >> rollno;
cout << "give name" << endl;
cin >> name;
cout << "give marks" << endl;
cin >> marks;
}
int GetRollno()
{
return rollno;
}
char * GetName()
{
return name;
}
int GetMarks()
{
return marks;
}
};
int main()
{
Student s1, s2;
s1.InputData();
s2.InputData();
s1.DispData();
s2.DispData();
cout <<"Rollno=" << s1.GetRollno() << endl;
s1.SetData(1, "abc", 80);
s1.DispData();
getch();
return 0;
}
Write a program with an encapsulated class Product (PId, PName, Qty) with functions
to set, display, input and get data. In main function, create 02 Product objects,
input and display their data.
Arrrays of Objects
-----------------
#include...
class Student
{
...
};
int main()
{
Student s[10];//Array of objects
int i;
cout << "Give Student data" << endl;
for (i=0; i<10; i++)
{
s[i].InputData();
}
cout << "You input" << endl;
for (i=0; i<10; i++)
{
s[i].DispData();
}
// code to display data of the students
// having marks in the range of 80 to 100
for (i=0; i<10; i++)
{
if (s[i].GetMarks() >= 80 &&
s[i].GetMarks() <=100 )
s[i].DispData();
}
getch();
return 0;
}
////////////////////////
Paper Work:
Write a program with an encapsulated class Product(PId, Pname, Price) with
functions to set, display, get and input data. In main function, create an array of
10 Product objects, input and dipslay their data.
int main()
{
Student s[10];//
int i, loc, highest;
cout << "Give Student data" << endl;
for (i=0; i<10; i++)
{
s[i].InputData();
}
loc = 0;
highest = s[0].GetMarks();
for (i=1; i<10; i++)
{
if (s[i].GetMarks() > highest)
{
highest = s[i].GetMarks();
loc = i;
}
}
cout << "Data of the student having the highest marks" << endl;
s[loc].DispData();
getch();
return 0;
}
Assignment:
Write a program with an encapsulated class Employee(EId, Ename, Salary) with
functions to set, display, get and input data. In main function, create an array of
10 Emplopyee objects, input and dipslay their data.
Paper/Lab Work:
Write a program with an encapsulated class Product (PId, Pname, Price). In main
function, input an array of 10 Product objects and display data of the product
having the lowest price.
//////////////////////////////
#include...
class Student
{
....
};
int main()
{
Student * s; // Pointer declaration
s = new Student[10];
// (s+0)->InputData();
// (s+1)->InputData();
int i;
for (i=0; i<10; i++)
{
(s+i)->InputData();
}
for (i=0; i<10; i++)
{
(s+i)->DispData();
}
delete [] s;
getch();
return 0;
}
Paper Work:
For Product (PId, PName, qty) scenario, create 10 Product objects using pointers,
input and display their data.
Quiz:
Write a program with an encapsulated class Employee (EId, Ename, Salary) with
functions to input, set, get and display data. In main function create 10 Employee
objects using pointers and display data of the Employee having the highest salary.
Assignment:
Write a program with an encapsulated class Vehicle (VId, ModelName, Price). In main
function create 10 Vehicle objects using pointers and display count of the Vehicles
having price in the range of 900000 to 1500000 and ModelName starting with 'M'.
if ((v+i)->GetPrice() >= 900000 &&
(v+i)->GetPrice() <= 1500000 &&
(v+i)->GetModelName()[0] == 'M' )
-------------------------------
Constructors
------------
The constructors contain code that is executed when an object is being created.
A constructor has the same name as that of class. It can not return a value.
Every class has a default constructor that exists when no constructor is written by
the programmer. The default constructor takes no arguments.
Example
-------
class A
{
int i;
public:
A()
{ cout << "Constructor with no args executed"
<< endl;
}
};
int main()
{
A a1;
getch();
return 0;
}
Overloading
-----------
int sum(int a, int b)
{
return a+b;
}
int sum(int a, int b, int c)
{
return a+b+c;
}
Constructor Overloading
-----------------------
The constructors can be overloaded by providing different number or types of
arguments.
e.g.
A()
{
cout << "Constructor with no args executed"
<< endl;
}
A(int a)
{
cout << "Constructor with 01 arg executed"
<< endl;
}
A(int a, int b)
{
cout << "Constructor with 02 args executed"
<< endl;
}
-------------------------------
Write a program with an encapsulated class Student (rollno, name, marks) having
appropriate constructors and functions to set, display, get and input data. In
main function create objects and display data.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class Student
{
int rollno;
char name[30];
int marks;
public:
Student()
{
rollno = 0;
strcpy(name,"");
marks = 0;
}
Student (int r, char * n, int m)
{
rollno = r;
strcpy(name,n);
marks = m;
}
void SetData(int r, char * n, int m)
{
rollno = r;
strcpy(name,n);
marks = m;
}
void DispData()
{
cout << "Rollno=" << rollno << endl;
cout << "Name=" << name << endl;
cout << "Marks=" << marks << endl;
}
void InputData()
{
cout << "give rollno" << endl;
cin >> rollno;
cout << "give name" << endl;
cin >> name;
cout << "give marks" << endl;
cin >> marks;
}
int GetRollno()
{
return rollno;
}
char * GetName()
{
return name;
}
int GetMarks()
{
return marks;
}
};
int main()
{
Student s1;
Student s2(7, "abcd", 85);
s1.DispData();
s2.DispData();
getch();
return 0;
}
---------------------------------
Practical Work:
Write a program with an encapsulated class Product (PId, Pname, Qty) having
appropriate constructors and functions to set, display, get and input data. In
main function create objects and display data.
------ ---------------------------
--------------------
Access Specifiers in C++
There are 03 access specifiers for class members
private
------
The members declared as private are accessible only within the class in which they
are declared. In C++ class, the members are private by default.
protected
---------
The members declared as protected are accessible in the class in which they are
declared and in the child class.
public
------
The members declared as public are accessible anywhere within the code.
----------------------------------
class A {
private:
int i;
protected:
int j;
public:
int k;
};
class B: public A
{
private:
int l;
protected:
int m;
public:
int n;
void DispData(){
//cout <<"i=" <<i << endl;
cout <<"j=" <<j << endl;
cout <<"k=" <<k << endl;
}
};
int main()
{
A a1;
//a1.i=7;
//a1.j=8;
a1.k = 9;
B b1;
//b1.i=6;
//b1.j=7;
b1.k=8;
// b1.l=9;
// b1.m=10;
b1.n=11;
getch();
return 0;
}
-------------------------------
Inheritance
Using inheritance data members and member functions are inherited to a child class.
In general, there are two types of inheritance:
Single Inheritance
In single inheritance, a child class may have only one parent. e.g. Java
class B extends A
Multiple Inheritance
In multiple inheritance, a child class may have more than one parent. e.g. C++
Example:
class B: private A
class B: public A, private C, public D
...
Destructors
-----------
The destructors contain code that is executed when an object is being destroyed.
The destructors can not be overloaded. It is used to perform finalization
activities.
closing files, closing network connections
class A
{
public:
~A()
{ cout <<"Object destroyed" << endl;
}
};
#include<iostream>
using namespace std;
#include<conio.h>
class A
{
public:
A(){cout << " A constructor with No args" << endl;
}
A(int i) {
cout << " A constructor with int args=" <<i << endl;
}
~A()
{
cout << "A dest" << endl;
}
};
class B: public A
{
public:
B(){
cout << "B no args" << endl;
}
B(int i):A(i){
cout << "B int args" << endl;
}
~B()
{cout <<"B object destroyed" << endl;
}
};
int main()
{
B b1(7);
getch();
return 0;
#include<iostream>
using namespace std;
#include<conio.h>
class A
{
int i;
protected:
int j;
public:
int k;
};
class B: public A
{
//j k
int l;
protected:
int m;
public:
int n;
};
class C: public B
{
};
int main()
{
A a;
B b;
C c;
//a.i=5;
//a.j=5;
a.k=5;
//b.i=5;
//b.j=5;
b.k=5;
//c.i=5;
//c.j=5;
c.k=5;
getch();
return 0;
}
#include<iostream>
using namespace std;
#include<conio.h>
class A
{
int i;
protected:
int j;
public:
int k;
};
class B: public A
{
public:
void dispIJK()
{
// cout << "i=" << i << endl;
cout << "j=" << j << endl;
cout << "k=" << k << endl;
}
};
class C: protected B
{
public:
void dispIJK()
{
// cout << "i=" << i << endl;
cout << "j=" << j << endl;
cout << "k=" << k << endl;
}
};
int main()
{
A a;
B b;
C c;
b.dispIJK();
c.dispIJK();
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class Student
{
protected:
int rollno;
char name[30];
Student()
{
rollno = 0;
strcpy(name, "");
}
Student(int rollno, char * name)
{
this->rollno = rollno;
strcpy(this->name, name);
}
void SetData(int rollno, char * name)
{
this->rollno = rollno;
strcpy(this->name, name);
}
void DispData()
{
cout << "Rollno=" << rollno << endl;
cout << "Name=" << name << endl;
}
void InputData()
{
cin >> rollno;
cin >> name;
}
int GetRollno()
{
return rollno;
}
char * GetName()
{
return name;
}
~Student()
{
cout << "Student memory de-allocated" << endl;
}
};
class StudentMCS: public Student
{
int BScMarks;
public:
StudentMCS()
{
BScMarks = 0;
}
StudentMCS(int rollno, char *name, int BScMarks):
Student(rollno, name)
{
this->BScMarks = BScMarks;
}
void SetData(int rollno, char * name, int BScMarks)
{
Student::SetData(rollno, name);
this->BScMarks = BScMarks;
}
void DispData()
{
Student::DispData();
cout << "BscMarks=" << BScMarks << endl;
}
void InputData()
{
Student::InputData();
cin >> BScMarks;
}
~StudentMCS()
{
cout <<"SMCS deleted" << endl;
}
int GetRollno()
{
return Student::GetRollno();
}
char * GetName()
{
return Student::GetName();
}
int GetBScMarks()
{
return BScMarks;
}
};
class StudentBCS: public Student
{
int FScMarks;
public:
StudentBCS()
{
FScMarks = 0;
}
StudentBCS(int rollno, char *name, int FScMarks):
Student(rollno, name)
{
this->FScMarks = FScMarks;
}
void SetData(int rollno, char * name, int FScMarks)
{
Student::SetData(rollno, name);
this->FScMarks = FScMarks;
}
void DispData()
{
Student::DispData();
cout << "FscMarks=" << FScMarks << endl;
}
void InputData()
{
Student::InputData();
cin >> FScMarks;
}
~StudentBCS()
{
cout <<"SBCS deleted" << endl;
}
int GetRollno()
{
return Student::GetRollno();
}
char * GetName()
{
return Student::GetName();
}
int GetFScMarks()
{
return FScMarks;
}
};
int main()
{
StudentMCS * m = new StudentMCS[2];
int i=0;
for (i=0; i<2; i++)
(m+i)->InputData();
for (i=0; i<2; i++)
(m+i)->DispData();
delete [] m;
/////////////////////////
StudentBCS * b = new StudentBCS[2];
for (i=0; i<2; i++)
(b+i)->InputData();
for (i=0; i<2; i++)
(b+i)->DispData();
delete [] b;
getch();
return 0;
}
// Assignment: Write code with encapsulated class Employee (EId, Ename). Use
inheritance for implementation of 02 child classes EmployeeRegular (ESalary) and
EmployeePartTime (EHours, ERate). In main, create 05 objects of both employees,
input and display their data.
-------------------
// Copy constructor
// A copy constructor receives as argument
// an object of the same class.
// When a copy of an object is created,
// the default copy constructor is called
// which copies each member data to new
// object's members.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
A(){}
A (A& a)
{
cout << "copy constructor called" << endl;
this->i = a.i;
}
};
int main()
{
A a1;
a1.setI(10);
A a2 = a1;
a2.dispI();
A a3(a2);
a3.dispI();
getch();
return 0;
}
---------------
Deep Copy
// Deep Copy
// When a copy of an object is created,
// the default copy constructor is called
// which copies each member data to new
// object's member. For pointer data,
// however, the pointer data must be
// re-initialized and then copied.
// It is accomplished using the programmer
// defined copy constructor which performs
// the Deep Copy.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
int * ptr;
public:
void setI(int i)
{
this->i = i;
}
void dispIPtr()
{
cout << "i=" << i<< endl;
cout << ptr[0] << " " << ptr[1] << endl;
}
A(){ptr = new int [2];
ptr[0] = 5; ptr[1] = 7;}
A (A& a)
{
cout << "copy constructor called" << endl;
this->i = a.i;
ptr = new int [2];
ptr[0] = 6; ptr[1] = 8;
}
};
int main()
{
A a1;
a1.setI(10);
a1.dispIPtr();
A a2 = a1;
a2.dispIPtr();
A a3(a2);
a3.dispIPtr();
getch();
return 0;
}
--------------------------
Nested Class in C++
In C++, a class can be embedded within another class. The members of a nested class
can be accessed by using reference of outer class.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class C1
{
int i;
public:
class C2
{
private:
int j;
public:
void setJ(int j)
{
this->j = j;
}
void dispJ()
{
cout << "j=" << j << endl;
}
};
private:
C2 c02;
public:
void setData(int i, C2 c02)
{
this->i = i;
this->c02 = c02;
}
void dispData()
{
cout << "i=" << i << endl;
c02.dispJ();
}
};
int main()
{
C1 c01;
C1::C2 c02;
c02.setJ(8);
c01.setData(5, c02);
c01.dispData();
getch();
return 0;
}
------------------------------
Friend Functions
A function declared to be a friend of a class can access private members of that
class.
e.g.
friend void function1();
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
friend void function1();
};
void function1()
{
A a;
a.i=10;
cout << "a.i=" << a.i << endl;
}
int main()
{
function1();
getch();
return 0;
}
Friend Classes
----------------
If a class Y is declared to be a friend of class X, then all methods of the class Y
can access private members of the class X.
// Friend classes
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
friend class B;
};
class B
{
public:
void function1()
{
A a;
a.i=10;
cout << " In function1, a.i=" << a.i << endl;
}
void function2()
{
A a;
a.i=10;
cout << "In function2, a.i=" << a.i << endl;
}
};
int main()
{
B b;
b.function1();
b.function2();
getch();
return 0;
}
------------------------------
Operator Overloading
-------------------
The existing C++ operators can be overloaded to make them work for other than pre-
defined data types. For instance, we can use ++ operator with objects in addition
to simple data types.
int i=5;
++i;
A a1,a2;
++a;
a2 = a1 + a2;
The operators can be overloaded by defining function using the following format:
}
e.g.
++i; i++; ++a;
A A::operator++(void)
{
++i;
return *this;
}
A a;
++a;
// Operator overloading
// Overloading Unary operators
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
A operator ++(void);
A operator ++(int);
};
A A::operator++(void)
{
++i;
return *this;
}
A A::operator++(int)
{
i++;
return *this;
/*
A a3;
i++;
a3.setI(i);
return a3;*/
}
int main()
{
A a;
a.setI(10);
++a;
a.dispI();
a++;
a.dispI();
A a5;
++a;
getch();
return 0;
}
// Operator overloading
// Overloading Binary operators
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
A operator +(A a0);
A operator -(A a0);
};
++a1
a3 = a1 + a2;
/*A a1, a2;
a1.setI(7);
a2.setI(5);
A a3;
a3 = a1 + a2;
*/
int k =5;
int i = 6;
int j = 7;
a3 = a1 + a2;
A A::operator + (A a0)
{
A a5;
a5.setI(this->i+a0.i);
return a5;
}
A A::operator - (A a0)
{
this->i = this->i - a0.i;
return *this;
}
/*A A::operator + (int k)
{
A a3;
a3.setI(this->i+k);
return a3;
}*/
int main()
{
A a1, a2, a3;
a1.setI(10);
a2.setI(20);
a3 = a1 + a2;
a3.dispI();
a3 = a1 - a2;
a3.dispI();
getch();
return 0;
}
cout << i << endl;
cout <<a2 ;
cin >> a2;
ostream cout;
// Operator overloading
// Overloading << and >> operators
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
int i;
public:
void setI(int i)
{
this->i = i;
}
void dispI()
{
cout << "i=" << i<< endl;
}
friend ostream & operator << ( ostream &os, const A &a);
friend istream & operator >> ( istream &is, A &a);
};
int main()
{
A a1;
cin >> a1;
cout << a1 << endl;
getch();
return 0;
}
Assignment:
1. Write an encapsulated class Student and
a) overload the operators ++, -- to perform pre and post increment/decrement in the
marks of the object and return the same object.
b) overload the operator * to multiply marks with an integer.
c) overload the << and >> operator to display all and input all data members of
Student
s2 = s1 * 2;
cout << s1<< endl;
cin >> s1;
Static Keyword
---------------
The static keyword is used with variables that retain their existence during
multiple calls of functions. In classes, the static keyword is used for class-level
members that may be accessed without using object reference.
Example
// Static data
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
static int i;
static void f1()
{
i++;
cout << "f1 called" << endl;
}
};
int A::i = 0;
int main()
{
A a;
a.i=5;
A a2;
A::i=7;
cout << a.i << " " << A::i << " " << a2.i << endl;
A::f1();
a.f1();
getch();
return 0;
}
// Exceptions
// Exceptions are the error conditions
// which may occur during execution of
// the program. An exception must
// be caught to avoid abnormal termination
// of the program. This is called
// exception handling.
// Exception Handling
// throw statement
// The throw statement is used to raise
// an exception.
// try-block
// The try block contains statements
// which may raise an exception.
// catch-block
// The catch block contains statements
// which are executed when an exception
// occurs. It contains the exception
// handler code.
// Built-in exceptions
// The C++ language contains a few
// built-in exceptions such as
// bad_alloc
// Programmer-defined exceptions
// A programmer may define his own
// exception by inheriting the exception
// class.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
int main()
{
int i, j;
cout << "Give i and j" << endl;
cin >> i >> j;
try{
if (j==0)
{
throw string("Division by zero");
} else
cout << "Result=" << i/j << endl;
}catch( string s)
{
cout << s << endl;
}
cout << "abc" << endl;
getch();
return 0;
}
// Exception Handling
// Built-in exceptions
// bad_alloc
// bad_cast
// bad_typeid
// bad_exception
// out_of_range
// invalid_argument
// overflow_error
// ios_base::failure
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
int main()
{
try{
float * f = new float [9900000000];
f[0] = 5;
cout << f[0] << endl;
delete [] f;
}catch( bad_alloc ba)
{
cout <<"Some error occured, Details:" << endl;
cout << ba.what() << endl;
}
getch();
return 0;
}
// Exception Handling
// Programmer-defined exceptions
// To implement the programmer defined
// exceptions, the built-in exception class
// must be inherited. The
// const char * what() function
// may be overriden in the child class
// to return customized error message.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
}catch(MyException me)
{
cout << me.what() << endl;
me.printError();
}
getch();
return 0;
}
// Exception Handling
// Catching all exceptions
try{
.....
....
} catch(Exception1 e){
} catch(Exception2 e){
}
try{
...
......
}catch(...){
}
//All exceptions may be caught by using
// ... in catch block arguments
//try{
//}catch(...)
//{
//}
Namespaces in C++
------------------
The namespaces are used to organize data and code to avoid ambiguities.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
namespace NS
{
string s1("first");
int p1=10;
void f1(){cout << s1 << endl;
}
}
using namespace NS;
int main()
{
cout << NS::s1;
NS::f1();
cout << p1 << endl;
getch();
return 0;
}
---------------------------------
// Early Binding and Late Binding
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
virtual void f1()
{
cout << "f1 of A called" << endl;
}
};
class B: public A
{
public:
void f1()
{
cout << "f1 of B called" << endl;
}
};
int main()
{
A * ptr;
A a2;
B b;
ptr = &a2;
ptr->f1();
ptr = &b;
ptr->f1();
getch();
return 0;
}
-----------------------------
// Runtime Polymorphism
// A method written in a base class
// is overridden by another method in
// derived class. A pointer to a base
// class is used with virtual keyword
// to decide which function to call at
// runtime. This is termed as
// runtime polymorphism.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
virtual void f1()
{
cout << "f1 of A called" << endl;
}
};
class B: public A
{
public:
void f1()
{
cout << "f1 of B called" << endl;
}
};
class C: public A
{
public:
void f1()
{
cout << "f1 of C called" << endl;
}
};
int main()
{
A * ptr;
B b;
C c;
ptr = &b;
ptr->f1();
ptr = &c;
ptr->f1();
getch();
return 0;
}
--------------------------
// Pure Virtual Functions and Abstract
// Classes
// A pure virtual function is a function
// without its implementation in a base
// class. e.g. virtual void f1() = 0;
// A class containing a pure virtual
// function is termed as an abstract class.
// It is not possible to create objects
// of an abstract class. A child class
// of an abstract class should implement
// the pure virtual functions of the
// parent abstract class otherwise the
// child class also becomes the abstract
// class.
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
class A
{
public:
virtual void f1() = 0;
};
class B: public A
{
public:
void f1()
{
cout << "f1 of B called" << endl;
}
};
class C: public A
{
public:
void f1()
{
cout << "f1 of C called" << endl;
}
};
int main()
{
//A a;
A * ptr;
B b;
C c;
ptr = &b;
ptr->f1();
ptr = &c;
ptr->f1();
getch();
return 0;
}
--------------------------
The Standard Template Library (STL)
----------------------------------
The Standard Template Library contains different data structures as containers
which can be used to store data.
The STL consists of
i) Containers
ii) Iterators
iii) Function objects
iv) Algorithms
Containers
-----------
The containers are built-in data structures in STL which are used to store
data.
Iterators
---------
Iterators in STL are used for traversal within containers.
vector <int>::iterator v;
Function Objects
---------------
Function objects are used to customize behavior of the algorithms in STL.
Algorithms
-----------
Different predefined algorithms such as those for sorting, searching, finding
minimum and maximum are given in STL.
while (!v.empty())
{
cout << v.top() << endl;
v.pop();
}
getch();
return 0;
}
#include<iostream>
using namespace std;
#include<conio.h>
#include<string.h>
#include<queue>
int main()
{
queue <int> v;
v.push(1);
v.push(2);
v.push(3);
v.pop();
while (!v.empty())
{
cout << v.front() << endl;
v.pop();
}
getch();
return 0;
}
--------------------
Virtual destructors
--------------------
In C++, if the delete keyword is used with the pointer to base class, then only the
destructor of the base class is called. Consequently, we have to use the virtual
keyword with the destructor of the base class to destroy both parts, i.e. the child
and the parent.
// Virtual Destructor
#include<iostream>
using namespace std;
#include<conio.h>
class A
{
protected:
int i;
public:
virtual ~A(){cout <<"Destructor A executed" << endl;
}
};
class B: public A
{
public:
~B(){cout <<"Destructor B executed" << endl;
}
};
int main()
{
A *a;
B *b = new B;
a = b;
delete a;
getch();
return 0;
}
In C++, using multiple inheritance, the ambiguity may occur while accessing member
of grandparent in th grandchild class. It is not clear to the compiler which copy
of the parent will be used in the grandchild class. Using the virtual keyword, the
virtual base classes share the same copy during inheritance which resolves the
ambiguity.
#include<iostream>
using namespace std;
#include<conio.h>
class A
{
protected:
int X;
};
class B: virtual public A
{
};
class C: virtual public A
{
};
class D: public B, public C
{
public:
int GetData()
{
return X;
}
void SetData(int X)
{
this->X = X;
}
};
int main()
{
D d;
d.SetData(50);
cout << "X=" << d.GetData() << endl;
getch();
return 0;
}
Assocations are represented by lines between classes with an arrow indicating the
direction.
Composition Example-2
-------
Person |
------
Aggregation example-2
EngineInspection Car
Engine Wheel
Generalization vs Specialization
-------------------------------
Generaliztion is combining similar classes into a single general class.
class C1{
};
class C2{
C1 c00;
};
C2 HAS-A C1
int main()
{
ofstream ofs ("f1.bin", ios_base::app);// Append ; Creation mode
Student s;
s.inputData();
ofs.write (reinterpret_cast<char*>(&s), sizeof(s));
ofs.close();
cout << "Data successfully written" << endl;
getch();
return 0;
}
int main()
{
ifstream ifs ("f1.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
cout << "*** The student data ***" << endl;
s.dispData();
}
ifs.close();
getch();
return 0;
}
void AddData()
{
Student s;
s.inputData();
ofstream ofs("student.bin", ios_base::app);
ofs.write(reinterpret_cast<char*>(&s), sizeof(s));
ofs.close();
cout << "Data successfully stored" << endl;
}
void DisplayData()
{
ifstream ifs ("student.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
cout << "*** The student data ***" << endl;
s.dispData();
}
ifs.close();
}
void ModifyData()
{
int r;
cout << "Enter rollno whose record is to be modified" << endl;
cin >> r;
ifstream ifs ("student.bin");
ofstream ofs ("temp.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
if (s.getRollno() == r)
{
s.inputData();
}
ofs.write (reinterpret_cast<char*> (&s), sizeof(s));
}
ifs.close();
ofs.close();
ofstream ofs2 ("student.bin");
ifstream ifs2 ("temp.bin");
while (ifs2.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
ofs2.write (reinterpret_cast<char*> (&s), sizeof(s));
}
ifs2.close();
ofs2.close();
cout << "Data successfully modified" << endl;
}
void DeleteData()
{
int r;
cout << "Enter rollno whose record is to be deleted" << endl;
cin >> r;
ifstream ifs ("student.bin");
ofstream ofs ("temp.bin");
Student s;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
if (s.getRollno() != r)
{
ofs.write (reinterpret_cast<char*> (&s), sizeof(s));
}
}
ifs.close();
ofs.close();
ofstream ofs2 ("student.bin");
ifstream ifs2 ("temp.bin");
while (ifs2.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
ofs2.write (reinterpret_cast<char*> (&s), sizeof(s));
}
ifs2.close();
ofs2.close();
cout << "Data successfully deleted" << endl;
}
void DisplayHighest()
{
ifstream ifs ("student.bin");
Student s;
int count = 0;
while (ifs.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
count++;
}
ifs.close();
Student s2[count];
ifstream ifs2 ("student.bin");
int i = 0;
while (ifs2.read (reinterpret_cast<char*> (&s), sizeof(s)))
{
s2[i] = s;
i++;
}
ifs2.close();
getch();
return 0;
}
class MyClass:
def method1(self):
print("Method1 called")
obj1 = MyClass()
obj1.method1()
obj1 = MyClass(7)
obj1.dispData()
s= Student()
s2 = Student(1,"abc", 78)
print("Marks=",s2.getMarks())
s.dispData()
s2.dispData()
########## List of Objects in Python
#List of objects
s3=[]
for i in range(0,3):
temp = Student()
s3.append(temp)
for i in range(0,3):
s3[i].inputData()
for i in range(0,3):
s3[i].dispData()
print("Marks=", s3[2].marks)
print("Marks=", s3[2].getMarks())
'''
Assignment: Write a program in Python with Product(PId, PName, Qty) class having
proper functions to set, input, display data with constructors and destructor.
Write code to input data of list of 10 Product objects and display the input data.
'''
#Inheritance
class Student:
rollno=0
name=""
def __init__(self,rollno=None,name=None):
if rollno == None:
self.rollno=0
self.name=""
else:
self.rollno=rollno
self.name=name
def setData(self, rollno, name):
self.rollno = rollno
self.name = name
def dispData(self):
print("Rollno=", self.rollno)
print("Name=", self.name)
def inputData(self):
self.rollno = int(input("Give rollno: "))
self.name = input("Give name: ")
def getName(self):
return self.name
def __del__(self):
print("Object deleted")
class StudentBCS(Student):
fscMarks=0
def __init__(self,rollno=None, name=None, fscMarks=None):
if rollno==None:
Student.__init__(self)
self.fscMarks=0
else:
Student.__init__(self,rollno, name)
self.fscMarks = fscMarks
def inputData(self):
Student.inputData(self)
self.fscMarks = int(input("Give Fsc marks: "))
def setData(self, rollno, name, fscMarks):
Student.setData(self, rollno, name)
self.fscMarks = fscMarks
def dispData(self):
Student.dispData(self)
print("FScmarks=", self.fscMarks)
def __del__(self):
print("deleted StudentBCS")
Student.__del__(self)
#List of objects
s3=[]
for i in range(0,3):
temp = StudentBCS()
s3.append(temp)
s3[i].inputData()
for i in range(0,3):
s3[i].dispData()
'''
Assignment: Write code in Python with encapsulated class Employee(EId, Ename). Use
inheritance for implementation of 02 child classes EmployeeRegular(ESalary) and
EmployeePartTime(EHours, ERate). In main code, create 05 objects of both
EmployeeRegular and Employee PartTime classes, input their data and display the
employee earning the highest salary.
'''
class Student:
rollno=0
name=""
marks=0
def __init__(self,rollno=None,name=None,marks=None):
if rollno == None:
self.rollno=0
self.name=""
self.marks=0
else:
self.rollno=rollno
self.name=name
self.marks=marks
def setData(self, rollno, name, marks):
self.rollno = rollno
self.name = name
self.marks = marks
def dispData(self):
print("Rollno=", self.rollno)
print("Name=", self.name)
print("Marks=", self.marks)
def inputData(self):
self.rollno = int(input("Give rollno: "))
self.name = input("Give name: ")
self.marks = int(input("Give marks: "))
def getMarks(self):
return self.marks
def __del__(self):
print("Object deleted")
#File processing
import pickle
#fp = open("student.bin","ab")
fp = open("student.bin","wb")
s= Student()
s2 = Student(1,"abc", 78)
s3= Student()
s3.inputData()
pickle.dump(s,fp,pickle.DEFAULT_PROTOCOL)
pickle.dump(s2,fp,pickle.DEFAULT_PROTOCOL)
pickle.dump(s3,fp,pickle.DEFAULT_PROTOCOL)
print("Data written to file")
fp.close()
print("Student file data")
try:
fp2 = open("student.bin","rb")
s = pickle.load(fp2)
while s:
s.dispData()
s = pickle.load(fp2)
except EOFError:
pass
fp2.close()
'''
Assignment: Write a program in Python with Product(PId, PName, Qty) class having
proper functions to set, input, display data with constructors and destructor.
Write code to input data of 10 Product objects, store the data to a binary file
"Product.bin". Write another program to read data from the binary file and display
it.
'''
#Reading data into List of objects
import pickle
class Student:
....
ar1 = []
s= Student()
try:
fp2 = open("student.bin","rb")
s = pickle.load(fp2)
while s:
s.dispData()
ar1.append(s)
s = pickle.load(fp2)
except EOFError:
pass
fp2.close()
# Display highest
high = ar1[0].marks
loc = 0
for i in range (1, len(ar1)):
if ar1[i].marks > high:
high = ar1[i].marks
loc = i
print("Data of student with highest marks")
ar1[loc].dispData()
'''
Assignment: Write a program in Python with Product(PId, PName, Qty) class having
proper functions to set, input, display data with constructors and destructor.
Write code to input data of 10 Product objects, store the data to a binary file
"Product.bin". Write another program to read data from the binary file and display
data of the student having the highest marks.
'''
Scope
------- Same Same different diff
class package package pack
subclass non-subcla
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
javac test0.java
java Test
General format:
package statements
import statements
classes and interfaces
*/
//package pk1;
import java.io.*;
import java.util.Scanner;
class Input{
//private int q = 0;
public static int getInt(){
int r=0;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
r = Integer.parseInt(s);
}catch(Exception e){}
return r;
}
public static float getFloat(){
float r=0;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
r = Float.parseFloat(s);
}catch(Exception e){}
return r;
}
public static String getString(){
String s="";
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
}catch(Exception e){}
return s;
}
}
class Test {
static int i=5;
public static void main(String args[]) {
System.out.println("Hello world");
Test2 t2 = new Test2();
t2.method1();
System.out.println("i="+i);
Student s = new Student();
s.setData(1,"abc",80);
s.dispData();
s.inputData();
s.dispData();
}
}
class Test2{
public void method1() {
System.out.println("method1 of Test2");
}
}
class Student {
int rollno;
String name;
int marks;
Student(){
rollno = 0;
name="";
marks = 0;
}
Student(int rollno, String name, int marks){
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
//a
//b
//b = a
// Garbage collector
//public void finalize() {
//}
public void setData(int rollno, String name, int marks){
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
public void inputData(){
System.out.println("give rollno, name, marks");
/*
rollno = Input.getInt();
name = Input.getString();
marks = Input.getInt();
*/
Scanner sc = new Scanner(System.in);
rollno = sc.nextInt();
sc.nextLine();
name = sc.nextLine();
marks = sc.nextInt();
}
public void dispData(){
System.out.println("Rollno="+rollno);
System.out.println("Name="+name);
System.out.println("Marks="+marks);
//...
}
public int getRollno(){
return rollno;
}
}
///////////////////
this keyword and super keyword
super()
for current object and parent object
////////////////////
Nested classes
class Outer
{
int outer_x = 100;
void test()
{
Inner in = new Inner();
in.test2();
}
class Inner
{
void test2()
{
System.out.println("Outer_x=" + outer_x);
}
}
}
class Test {
public static void main(String args[]) throws Exception {
Outer o = new Outer();
o.test();
}
}
/////////////////////
/*
String class in Java
-----------------------
String s0 = new String ("abc"); // new created
String s1 = "abc"; //a string is allocated from a pool
String s2 = "abc";
Write a program to input a string, and display its first and last character.
///String class
if ((s3.startsWith("ab"))
....
String s = "abcdefcgh";
String s2 ="fc";
int k = s.indexOf(s2,7);
int i = s. indexOf('c');
int i = s. lastIndexOf('c');
Write a program to input two strings s1 and s2, and display all occurrences of s2
in string s1.
String s6 = s3.substring(1);
String s = s3.concat("ghi");
SOP(2+"abc"+4);
StringBuffer reverse()
SOP(sb.reverse())
StringBuffer delete (int startIndex, int endIndex)
StringBuffer deleteCharAt(int location)
String s= "abbbbbbbbbadfasdf";
StringBuffer sb= new StringBuffer(s);
inser
delete
replace
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String s = sb.substring(0);
/*
File Processing In Java
a) Byte Streams in Java
FileOutputStream
FileInputStream
0 to 127 ASCII
65 A
b) Character Streams in Java
FileWriter
FileReader
0 to 65535
Unicode
*/
import java.io.*;
class Test
{
public static void main(String args[]) throws Exception
{
String s3;
FileReader fr = new FileReader("a.txt");
BufferedReader br = new BufferedReader(fr);
while ((s3= br.readLine())!=null)
{
System.out.println(s3);
}
br.close();
fr.close();
}
}
// Write a program to input data of 10 Student (rollno, name, marks) objects. Write
code to store data on text file "student.txt". Also write code to read data from
the file and display the students whose name starts with "A".
class Test2
{
public static void main(String args[]){
Frame fr = new Frame ("My Window Title");
Button b1 = new Button("First");
TextField tf = new TextField();
fr.setLayout(null);
b1.setBounds(100,100,50,50);
tf.setBounds(160,100,150,50);
//left top width height
fr.add(b1);
fr.add(tf);
b1.addActionListener (new MyListener());
fr.addWindowListener (new MyListener2());
//fr.show();
//fr.pack();
fr.setSize(300,200);
fr.setVisible(true);
}
}
// ActionListener interface
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("button clicked");
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
class Test2
{
static JLabel l1;
static JButton b1;
static JButton b2;
//fr.show();
//fr.pack();
fr.setSize(400,400);
fr.setVisible(true);
}
}
// ActionListener interface
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String s0 = ae.getActionCommand();
if (s0.equals("First")) {
System.out.println("button b1 clicked");
Test2.l1.setText("New Message");
} else if (s0.equals("Second")) {
String s = Test2.l1.getText();
System.out.println(s);
Test2.b1.setLabel("Yes");
}
}
}
class MyListener2 extends WindowAdapter {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
class Database
{
static Connection cn;
static JTextField t1, t2, t3;
public static void main(String args[]){
JFrame fr = new JFrame ("My Window Title");
JButton b1 = new JButton("First");
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
fr.setLayout(null);
b1.setBounds(100,100,150,50);
t1.setBounds(10,10,150,50);
t2.setBounds(160, 10, 150, 50);
t3.setBounds(310, 10, 150, 50);
fr.add(b1);
fr.add(t1);
fr.add(t2);
fr.add(t3);
// Create Connection
try{
/* Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access
Driver(*.mdb)};DBQ=db1.accdb;";
//DriverManager.getConnection//(database, "mak", "mak");
*/
Class.forName("com.mysql.jdbc.Driver").newInstance();
String database = "jdbc:mysql://localhost/mak1?";
cn =
DriverManager.getConnection(database, "root", "");
// root, ""
}catch(Exception e){
System.out.println(e);
}
// Select Query
String q2 = "Select * from Student";
ResultSet rs =null;
rs = s.executeQuery(q2);
while (rs.next())
{
System.out.println("Rollno=" + rs.getString(1));
System.out.println("Name=" + rs.getString(2));
System.out.println("Marks=" + rs.getString(3));
}
s.close();
}catch(Exception e){
System.out.println(e);
}
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
/* Develop program to manage
employee data to perform the following functionality
Project
-------
Menu
=>Product (PID, Pname, StockQty)
Add Product
Modify Product
Delete Product
Search
=>Balance
View Stock Balance
Search product balance
*/
/*
Command line arguments
-----------------------
int main(int argc, char * argv[])
{
}
*/
class Test {
public static void main(String args[]) {
int i=0;
for (i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
/*
Inheritance in Java
-------------
The data and methods can be inherited to child class.
Parent class is called base class and child class is called derived class. The code
written in parent class can be reused in child class.
Private Members
---------------
A child class access can access all members of its parent except the private
members.
private int i;
Super Keyword
-------------
In java, the super keyword is used to access members of the parent class.
*/
class A{
int i, j;
void dispIJ()
{
System.out.println("i=" +i + "j=" +j);
}
}
/// overriding
/*The dispIJ method of the parent class has been overridden with the new
implementation in the child class.*/
class B extends A{
int k; int i;
void dispK()
{
System.out.println("k=" + k);
}
void dispIJ()
{
super.dispIJ();
System.out.println("i="+i+"j="+j);
}
void showSum()
{
System.out.println("Sum=" + (super.i+j+k));
}
}
class Test {
public static void main(String args[]) {
A a = new A();
a.i = 10; a.j = 40;
a.dispIJ();
/////////
B b = new B();
b.i= 20;
b.j= 30;
b.k = 30;
b.dispK();
b.showSum();
b.dispIJ();
}
}
/*
Constructors in Inheritance
-------------
*/
class A{
int i, j;
A()
{System.out.println("A Constructor with no args");
}
A(int i)
{System.out.println("A Constructor with int args");
}
}
class B extends A{
B()
{System.out.println("B Constructor with no args");
}
B(int i)
{ super(i);
System.out.println("B Constructor with int args");
}
}
////////////
Exceptions in Java
Definition
throw keyword
----------
it is used to raise an exception
class TestE {
public static void main(String args[]) {
try{
method1();
System.out.println("program completed");
}catch(Exception e) {
System.out.println(e);
}
}
public static void method1() throws Exception {
method2();
System.out.println("last method1");
}
public static void method2() throws Exception{
int i = 5;
int j = 0;
System.out.println(i/j);
}
}
Java's Builtin Exception
------------------------
Unchecked Exceptions
ArithmeticException
ArrayIndexOutofBoundsException
ArrayStoreException
ClassCastException
IllegalArgumentExceoption
IllegalMonitorStateException
IndexOutOfBoundsException
NegativeArraySizeExceoption
NullPointerException
NumberFormatException
-------------------
Checked Exceptions
ClassNotFoundException
CloneNotsupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodExceoption
try{
obj1.method1();
}catch(Exception e){
...
}
/*
// Threads in Java
Java supports multi-threading for concurrent execution of tasks. A thread
represents a sequence of execution. There is always a main thread executing when
the main function is executed. There are two ways for creating threads in java.
a) Implementing Runnable interface
b) Extending Thread class
public void run()*/
mt1.start();
mt2.start();
mt1.join();
mt2.join();
System.out.println("Main completed");
}
}
Java AWT/SWING
--------------------
AWT
--------------
class Test2
{
public static void main(String args[]){
Frame fr = new Frame ("My Window Title");
Button b1 = new Button("First");
TextField tf = new TextField();
fr.setLayout(null);
b1.setBounds(100,100,50,50);
fr.add(b1);
fr.add(tf);
//fr.show();
//fr.pack();
fr.setSize(300,200);
fr.setVisible(true);
}
}
// ActionListener interface
class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("button clicked");
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
---------------------
SWING and Databases
---------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
class Database
{
static Connection cn;
static JTextField t1, t2, t3;
public static void main(String args[]){
JFrame fr = new JFrame ("My Window Title");
JButton b1 = new JButton("First");
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
fr.setLayout(null);
b1.setBounds(100,100,150,50);
t1.setBounds(10,10,150,50);
t2.setBounds(160, 10, 150, 50);
t3.setBounds(310, 10, 150, 50);
fr.add(b1);
fr.add(t1);
fr.add(t2);
fr.add(t3);
// Create Connection
try{
/* Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access
Driver(*.mdb)};DBQ=db1.accdb;";
//DriverManager.getConnection//(database, "mak", "mak");
*/
Class.forName("com.mysql.jdbc.Driver").newInstance();
String database = "jdbc:mysql://localhost/mak1?";
cn =
DriverManager.getConnection(database, "root", "");
// root, ""
}catch(Exception e){
System.out.println(e);
}
// Select Query
String q2 = "Select * from Student";
ResultSet rs =null;
rs = s.executeQuery(q2);
while (rs.next())
{
System.out.println("Rollno=" + rs.getString(1));
System.out.println("Name=" + rs.getString(2));
System.out.println("Marks=" + rs.getString(3));
}
s.close();
}catch(Exception e){
System.out.println(e);
}
}
}
class MyListener2 extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
/* Develop program to manage
employee data to perform the following functionality
Project
-------
Menu
=>Product (PID, Pname, StockQty)
Add Product
Modify Product
Delete Product
Search
=>Balance
View Stock Balance
Search product balance
*/