C (Jan-2010)
C (Jan-2010)
Initialization of variables
// initialization of variables #include<iostream> using namespace std; int main () { int a=5; // initial value = 5 int b(2); // initial value = 2 int result; // initial value undetermined a = a + 3; result = a - b; cout << result; return 0; } Output: 6
Operators
1. Assignment (=) 2. Arithmetic operators ( +, -, *, /, % ) 3. Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) 4. Increase and decrease (++, --) 5. Relational and equality operators ( ==, !=, >, <, >=, <= ) 6. Logical operators ( !, &&, || ) 7. Conditional operator ( ? ) 8. Comma operator ( , ) 9. Bitwise Operators ( &, |, ^, ~, <<, >> ) 10.Explicit type casting operator 11.sizeof() 12.Scope Resolution operator
Comma operator ( , ) The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. For example, the following code: a = (b=3, b+2); Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.
sizeof() This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object: a = sizeof (char); This will assign the value 1 to a because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution.
Scope Resolution operator #include <iostream> double a = 128; int main () { double a = 256; cout << "Local a: " << a << endl; cout << "Global a: " << ::a << endl; return 0; }
You can define your own names for constants that you use very often #define preprocessor directive. Its format is: #define identifier value For example: #define PI 3.14159265 #define NEWLINE '\n'
// defined constants: calculate circumference #include <iostream> using namespace std; #define PI 3.14159 #define NEWLINE '\n int main () { double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; } Output: 31.4159
Functions A function is a group of statements that is executed when it is called from some point of the program. The following is its Syntax / format: type name ( parameter1, parameter2, ...) { statements }
// function example #include <iostream> using namespace std; int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; }
The result is 8
Passing by reference is also an effective way to allow a function to return more than one value. For example, here is a function that returns the previous and next numbers of the first parameter passed.
// more than one returning value #include <iostream> using namespace std; void prevnext (int x, int& prev, int& next) { prev = x-1; Output: next = x+1; Previous=99, Next=101 } int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; }
Default values in parameters. When declaring a function we can specify a default value for each parameter. This value will be used if the corresponding argument is left blank when calling to the function. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. For example:
// default values in functions #include <iostream> using namespace std; int divide (int a, int b=2) { int r; r=a/b; return (r); } int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; }
Output : 6 5
Overloaded functions.
In C++ two different functions can have the same name if their parameter types or number are different. This is called Function overloading. For example:
// overloaded function #include <iostream>using namespace std; int operate (int a, int b) { return (a*b); } Output: float operate (float a, float b) 10 { return (a/b); } 2.5 int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; }
#include <iostream> int main () { double a; cout << "Type a number: "; cin >> a; { int a = 1; a = a * 10 + 4; cout << "Local number: " << a << endl; } cout << "You typed: " << a << endl; return 0; }
// Simple declaration of i
for (int i = 0; i < 4; i++) // Local declaration of i { cout << i << endl; // This outputs 0, 1, 2 and 3 } cout << i << endl; return 0; } // This outputs 487
0 1 2 3 487
#include <iostream> int main () { for (int i = 0; i < 4; i++) { cout << i << endl; } cout << i << endl; i += 5; cout << i << endl; } return 0;
#include <iostream> int main () { double a = 3.1415927; double & b = a; b = 89; cout << "a contains: " << a << endl; } return 0; // b is a
#include <iostream> void change (double *r, double s) { *r = 100; s = 200; } int main () { double k, m; k = 3; m = 4; change (&k, m); cout << k << ", " << m << endl; return 0; } Output: 100, 4.
Classes A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
Classes are generally declared using the keyword class, with the following format: class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;
An access specifier is one of the following three keywords: private, public or protected.
private members of a class are accessible only from within other members of the same class or from their friends. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. Finally, public members are accessible from anywhere where the object is visible.
class CRectangle { int x, y; public: void set_values(int,int); int area (void); } rect;
// classes example with one object #include <iostream> class CRectangle { int x, y; public: void set_values (int,int); int area () { return (x*y); } };
// member Function
void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } Output: area: 12
The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class declaration itself. One of the greater advantages of a class is that, as any other type, we can declare several objects of it. For example, following with the previous example of class CRectangle, we could have declared the object rectb in addition to the object rect:
// example: one class, two objects #include <iostream.h> class CRectangle { int x, y; public: void set_values (int,int); int area () { return (x*y); } };
void CRectangle::set_values (int a, int b) { x = a; y = b;} Output int main () rect area: 12 { CRectangle rect, rectb; rectb area: 30 rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }
Declaration of Class Define a Class as Day, month and year of a member data variable without any method or any member function
Class date { private : // by default members are private int day; int month; int year; } today;
3) Class sample { private: int x, y; public: void setdata(); void getdata(); void display(); void setdata(); }; 4) Class sample { private: int fact; public: int fact(); };
// error, same name cannot be used for both data and function member;
How a data member and member functions are defined in C++. Class sample { private: int x, y; public: int sum() { return(x+y); } int diff() { return(x-y); } };
Note: The Local Members can be defined within the class declaration
Declaring a member function of a class outside its scope In C++ the member function can be declared inside or outside of the class declaration. Note: If the member function is declared outside of the class then the Scope resolution operator(::) is used.
Class sample { private: int x, y; public: int sum(); int diff(); }; Int sample :: sum() { return(x+y); } Int sample :: diff() { return(x-y); }
Class first { private: int x, y; public: int sum(); int diff(); } one; Class second { private: int x, y; public: int sum(); int diff(); } two;
Class student { private: int rno; int age; char sex; float height; float weight; public: void getinfo(); void disinfo(); void process(); void personal(); }; student mech, comp, civil, elex
WAP in C++ to assign data to the data member of a class such as day, month, year and to display the contents of the class on the screen.
#include<iostream.h> Here the data members Class date { are Public, by default the public : data members are int day, month, year; private. Private members }; can not be access Void main() outside the class. { class date today; cin>>today.day>>today.month>>today.year; cout<< Todays Date is =<<today.day<< / << today.month << / << today.year; }
WAP in C++ to demonstrate how to define the both data member and member function of a class within the scope of class definition.
#include<iostream.h> Class date { private : int day, month, year; public : void getdata(int d, int m, int y) { day=d; month=m; year=y; } void display() { cout<< Todays date is = << day << / << month << / << year << endl; };
Void main() { class date today; int d1,m1,y1; d1=15; m1=9; y1=2007; today.getdat(d1,m1,y1); today.display(); }
WAP in C++ to read the data variables of a class by the member function of a class and display the contents of the class objects on the screen.
#include<iostream.h> Class date { private : int day, month, year; public : void getdata() { cout << enter the date << endl; cin >> day >> month >> year; } void display() { cout<< Todays date is = << day << / << month << / << year << endl; };
WAP in C++ for simple arithmetic operations such as addition, subtraction, multiplication & division using a #include<iostream.h> member function of a class. These methods are defined Class sample { Private:the scope of a class definition. within
int x; int y; Public: Void getinfo() { Cout << enter any two numbers ? << endl; Cin >> x >>y; Void display() { Cout << x = << x << endl; Cout << y = << y << endl; Cout << sum = << sum() << endl; Cout << dif = << dif() << endl; Cout << mul = << mul() << endl; Cout << div = << div() << endl; }
int sum() { return(x+y); } int diff() { return(x-y); } int mult() { return(x*y); } int div() { return(x/y); } }; // end of class definition
WAP in C++ for simple arithmetic operations such as addition, subtraction, multiplication & division using a member function of a class. These methods are defined out of the scope of a class definition.
#include<iostream.h> Class sample { Private: int x; int y; Public: Void getinfo(); Void display(); int sum(); int diff(); int mul(); int div(); };
Void sample :: getinfo() { Cout << enter any two numbers ? << endl; Cin >> x >>y; Void sample :: display() { Cout << x = << x << endl; Cout << y = << y << endl; Cout << sum = << sum() << endl; Cout << dif = << dif() << endl; Cout << mul = << mul() << endl; Cout << div = << div() << endl; }
int sample :: sum() { return(x+y); } int sample :: diff() { return(x-y); } int sample :: mult() { return(x*y); } int sample :: div() { return(x/y); }
WAP to declare a class sample containing data member roll no and percentage. Accept and display this information for 2 objects of class.
#include<iostream.h> class sample { private: int roll; float per; public: void getdata(); void display(); }; void sample :: getdata() { cout<<"pls. enter the roll No & percentage"<<endl; cin>>roll>>per; }
void sample :: display() { cout<< "roll no=" << roll << endl; cout << "percentage" << per <<endl; } void main() { sample obj1,obj2; obj1.getdata(); obj2.getdata(); obj1.display(); obj2.display(); }
#include<iostream.h> class sample { private: int roll; float per; public: void getdata(); { cout << Pls. enter roll no & per <<endl; cin>>roll>>per; }
void display() { cout<< "roll no=" << roll << endl; cout << "percentage" << per <<endl; } }; void main() { sample obj1,obj2; obj1.getdata(); obj2.getdata(); obj1.display(); obj2.display(); }
void sample :: display() { cout<< "roll no=" << roll << endl; cout << "percentage" << per <<endl; } void main() { sample obj[5]; for(int i=0;i<5;i++) obj[i].getdata(); for(i=0;i<5;i++) obj[i].display(); }
WAP to declare a class sample containing data member roll no and percentage. Accept this information for 2 objects of class and display the roll no of the object having higher percentage.
#include<iostream.h> class sample { private: int roll; float per; public: void getdata() { cin>>roll>>per; } void display() { cout<< "roll no=" << roll << endl; cout << "percentage" << per <<endl; }
void hg(sample obj1,sample obj2) { if(obj1.per>obj2.per) obj1.display(); else obj2.display(); } }; void main() { sample obj1,obj2,obj3; obj1.getdata(); obj2.getdata(); obj3.hg(obj1,obj2); }
#include<iostream.h> class sample { public: // Instead of private should be public for this probl. int roll; float per; public: void getdata() { cin>>roll>>per; } void display() { cout<< "roll no=" << roll << endl; cout << "percentage" << per <<endl; } };
void main() { sample obj1,obj2; obj1.getdata(); obj2.getdata(); if (obj1.per > obj2.per) obj1.display(); else obj2.display(); }
WAP to declare a class account having data members as account_no and balance. Accept this data for 5 accounts and display the data of the accounts having balance greater than 2000.
#include<iostream.h> class account { private: int accno; float bal; public: void getdata(); void putdata(); }; void account::getdata() { cout << "Enter the Account_no"<<endl; cin >> accno; cout << "Enter the Balance"<<endl; cin >> bal; }
void account::putdata() { if(bal > 2000) { cout << "Account_no "<<accno<<endl; cout << "Balance "<< bal<<endl; } } void main() { int i; account a[5]; for(i=0;i<5;i++) a[i].getdata(); for(i=0;i<5;i++) a[i].putdata(); }
void employee::putdata() { cout << "Employee Name= "<<name<<endl; cout << "Basic Salary = "<<bs<<endl; cout << "Gross Salary = "<<gs()<<endl; } float employee::gs() { float hra,da,gross; hra=bs*0.15; da=bs*0.445; gross=hra+da+bs; return(gross); }
void worker::putdata() { if((strcmp(skill,"plumber"))==0) cout << "Worker Name = "<<name<<endl; } void main() { int i; worker w[3]; for(i=0;i<3;i++) w[i].getdata(); cout << "Workers Having Skill plumber are"<<endl; for(i=0;i<3;i++) w[i].putdata(); }
#include<iostream.h> #include<string.h> class result { private: char name[30],grade; float m1,m2,m3,avg; public: void getdata(); void putdata(); };
void result::getdata() { cout << "Enter the Name of Student"<<endl; cin >> name; cout << "Enter the Marks m1,m2,m3"<<endl; cin >> m1>>m2>>m3; avg=(m1+m2+m3)/3; if(avg>=75) grade='A'; if((avg<75)&&(avg>=60)) grade='B'; if((avg<60)&&(avg>=40)) grade='C'; cout<<"Average= "<<avg<<endl; cout<<"Grade= "<<grade<<endl; }
void result::putdata() { if(avg>=75) cout << "Name = "<<name<<endl; } void main() { int i; result s[3]; for(i=0;i<3;i++) s[i].getdata(); cout << "Name of Students Having A grade are"<<endl; for(i=0;i<3;i++) s[i].putdata(); }
Constructor
Definition: A constructor is a special member function for automatic initialization of an object. i.e whose task is to initialize the data member when an object is declared. Syntax rules for writing constructor functions. 1. A constructor name must be the same as that of its class name. 2. It is declared with no return type not even void. 3. It cannot be declared const. 4. It may not be static. 5. It may not be Virtual. 6. It should be Public or Protected.
The general Syntax of the constructor function in C++ is Class class_name { private: type data_memeber1; _________________ Protected: _________________ _________________ Public: class_name(); // Constructor __________________ __________________ }; class_name::class_name() { __________________ __________________ }
Example of Constructor declaration in a class definition Class employee { private: char name[20]; int empno; float sal; Public: employee(); // Constructor void getdata(); void display(); }; employee( ) :: employee( ) { cout << class employee constructor is created<<endl; name=Sunita; empno=1; sal=10000; }
#include<iostream.h> class employee { private: char *ename; int empno; float sal; public: employee(); // Constructor void putdata(); }; employee::employee() { cout << "class employee constructor is created"<<endl; ename="Sunita"; empno=1; sal=10000; }
void employee :: putdata() { cout<<ename<<endl; cout<<empno<<endl; cout<<sal; } void main() { employee e1; e1.putdata(); }
WAP to generate a series of Fibonacci numbers using the constructor member function.
#include<iostream.h> class fibonacci { private: int n,c,f1,f2,f3; public: fibonacci(); void getdata(); void putdata(); }; fibonacci::fibonacci() { f1=0; f2=1; }
// Constructor
void fibonacci:: getdata() { cout<<"Pls. enter total no. of series."<<endl; cin>>n; cout<<f1<<endl; cout<<f2<<endl; } void fibonacci:: putdata() { for(c=3;c<=n;c++) { f3=f1+f2; cout<<f3<<endl; f1=f2; f2=f3; } }
Default Constructors
The default constructor is a special member function which is invoked by the C++ compiler without any argument for initializing the objects of a class. i.e a default constructor function initializes the data memebers with no arguments.
The general Syntax of the default constructor function in C++ is Class class_name { private: type data_memeber1; _________________ _________________ Public: class_name(); // default Constructor __________________ __________________ }; class_name::class_name() { } // without any arguments
Example of default constructor Class employee { private: char name[20]; int empno; float sal; Public: employee(); // default Constructor void getdata(); void display(); }; employee( ) :: employee( ) { name[0]=\0 empno=0; sal=0.0; }
#include<iostream.h> class employee { private: char ename[20]; int empno; float sal; public: employee(); // default Constructor void putdata(); }; employee::employee() { cout << "class employee default constructor is created"<<endl; ename[0]='\0'; empno=0; sal=0; }
void employee :: putdata() { cout<<ename<<endl; cout<<empno<<endl; cout<<sal; } void main() { employee e1; e1.putdata(); }
#include<iostream.h> class employee { private: char ename[20]; int empno; float sal; public: employee(); void putdata(); };
// default Constructor
employee::employee() { } // this is must void employee :: putdata() { cout<<ename<<endl; cout<<empno<<endl; cout<<sal; } void main() { employee e1; e1.putdata(); }
In C++ we can pass default values to the functions. Constructors are also the functions, hence they also posses the same property. We can pass default values to the constructors also. for example
// Example of Constructor with default argument #include<iostream.h> class employee { private: int empno; float sal; public: employee(int,float); // default Constructor void putdata(); };
employee::employee(int no,float s=0) { empno=no; sal=s; } // this is must void employee :: putdata() { cout<<empno<<endl; cout<<sal; } void main() { employee e1(1); e1.putdata(); }
// Example of Constructor with default argument #include<iostream.h> class employee { private: char *ename; int empno; float sal; public: employee(char*,int,float); // default Constructor void putdata(); }; employee::employee(char *nm,int no,float s=0) { ename=nm; empno=no; sal=s; } // this is must
void employee :: putdata() { cout<<ename<<endl; cout<<empno<<endl; cout<<sal; } void main() { employee e1("sunita",1); e1.putdata(); }
Parameterized Constructor
Note that the Constructors do not take any parameters & hence always initializes all the objects of the class with the same values. The parameterized constructors accept the parameters and these parameters are then used to initialize the data members. If we want to initialized different objects with different initialization values then we have to used parameterized constructor.
#include<iostream.h> class employee { private: char *ename; int empno; float sal; public: employee(char*,int,float); // parameterized Constructor void putdata(); }; employee::employee(char *nm,int no,float s=0) { ename=nm; empno=no; sal=s; } // this is must
void employee :: putdata() { cout<<"\n"<<ename<<endl; cout<<empno<<endl; cout<<sal; } void main() { employee e1("sunita",1); employee e2("Zeba",1); e1.putdata(); e2.putdata(); }
Copy Constructor
Copy constructors are always used when the compiler has to create a temporary object of a class object. The constructor cannot take the parameter of the same class type. For example, sample :: sample(sample objectname) { ________ ________ }
Copy constructor allows you to have the object of the same class type but with reference operator. sample :: sample(sample & objectname) { ________ ________ } sample obj2 (obj1); or sample obj2=obj1; sample obj1; obj2=obj1; // Invalid copy construct.
#include<iostream.h> class employee { private: char *ename; int empno; float sal; public: employee(char*,int,float); void putdata(); employee(employee &); };
employee::employee(char *nm,int no,float s=0) { ename=nm; empno=no; sal=s; } // this is must void employee :: putdata() { cout<<"\n"<<ename<<endl; cout<<empno<<endl; cout<<sal; }
employee::employee(employee & obj) { ename=obj.ename; empno=obj.empno; sal=obj.sal; } void main() { employee e1("zeba",1); e1.putdata(); employee e2(e1); e2.putdata(); }
Destructor Definition: A destructor is a function that automatically executes when an object is destroyed. A destructor function gets executed whenever an instance of the class to which it belongs goes out of existence. The primary usage of the destructor function is to release space on the heap.
Syntax rules for writing a destructor functions. 1.A destructor function name is the same as the class it belongs except that the first character of the name must be a tilde(~). 2.It is declared with no return type not even void. 3.It cannot be declared const. 4.It should be Public or Protected.
The general Syntax of the destructor function in C++ is Class class_name { private: type data_memeber1; _________________ Protected: _________________ _________________ Public: class_name(); // Constructor ~class_name(); // Destructor __________________ }; class_name::class_name() { __________________ __________________ }
Example of destructor declaration in a class definition Class employee Void main() { private: { char *name; employee e1; int empno; float sal; getch(); Public: employee(); // Constructor } ~employee(); // Destructor void getdata(); void display(); }; employee( ) :: employee( ) { cout << class employee constructor is created<<endl; name=Sunita; empno=1; sal=10000; } employee( ) :: ~employee( ) { cout << Data base has been deleted<<endl; }
INLINE MEMBER FUNCTION The inline keyword is used only in the function declarations. The advantages of using inline member functions are: The Size of the object code is reduced. it increases the execution speed and the inline member function are compact function call.
The general Syntax of the inline member function in C++ is class class_name { private: type data_memeber1; _________________ Public: inline return_type function_name(parameters); inline return_type function_name(parameters); __________________ __________________ };
Whenever a function is declared with the inline specifier, the c++ compiler replaces it with the code itself so the overhead of the transfer of control between the calling portion of a program and a function is reduced.
#include<iostream.h> #include<string.h> #include<conio.h> class sample { private: int x; public: inline void getdata(); inline void putdata(); }; inline void sample::getdata() { cout<<"enter any Number"<<endl; cin>>x; }
inline void sample::putdata() { cout<<"the Entered Number is " <<x; } void main() { clrscr(); sample obj; obj.getdata(); obj.putdata(); getch(); }
OUTPUT:
Friend Function The main function of the object oriented programming are data hiding & data Encapsulation. Whenever data variables are declared in a private category of a class, the non-member functions are restricted from accessing these variables. The private data values can neither be read nor be written by non member functions.
If any attempt is made directly to access these members, the compiler will display an error message as inaccessible data type. The best way to access a private data member by a non member function is to change a private data member to a public group. To solve this problem, a friend function can be declared to have access to these data members,
Friend is a special mechanism by which a non-member function can access private data. A friend function may be declared within the scope of a class definition. The keyword friend inform the compiler that it is not a member function of the class.
The general syntax of the friend function is Friend return_type function_name(parameter); Case 1: friend function is defined within the scope of a class definition.
class sample { Private: Int x; Public: void getdata(); friend void display(sample abc) { cout << value of x=<<abc.x<<endl; } };
// Example of friend function defined within the scope the class definition #include<iostream.h> class test { private: int x; public: void getdata(); friend void putdata(class test obj) { cout<<obj.x<<endl; } };
void test:: getdata() { cin>>x; } void main() { test obj; obj.getdata(); putdata(obj); }
// Example of friend function defined out of scope the class definition #include<iostream.h> class test { private: int x; public: void getdata(); friend void putdata(class test); }; void test:: getdata() { cin>>x; }
void putdata(class test obj) { cout<<obj.x<<endl; } void main() { test obj; obj.getdata(); putdata(obj); }
Note: If the friend function is defined within the scope of the class definition, then the inline code substitution is automatically made. If it is defined outside the class definition, then it is required to precede the return type with the keyword inline in order to make an inline code substitution.
/ Example of friend function defined out of scope the class definition #include<iostream.h> class test { private: int x; public: inline void getdata(); friend void putdata(class test); }; inline void test:: getdata() { cout<<"enter any number\t"; cin>>x; }
inline void putdata(class test obj) { cout<<"the Entered no. is \t"; cout<<obj.x<<endl; } void main() { test obj; obj.getdata(); putdata(obj); }
Granting Friendship to another class A class can have friendship with another class. For example Let there be two classes, first and second. If the class first grants its friendship with the other class second, then the private data members of the class first are permitted to be accessed by the public members of the class second. But on the other hand, the public member functions of the class first cannot access the private members of the class second.
// Example of friend function granting friendship to another class. #include<iostream.h> class first { friend class second; private: int x,y; public: void getdata(); }; class second { public: void putdata(class first ff); };
void first :: getdata() { cout<<"enter any two numbers\n"; cin>>x>>y; } void second::putdata(class first ff) { int sum; sum=ff.x+ff.y; cout<<"Sum="<<sum; } void main() { first ff; second ss; ff.getdata(); ss.putdata(ff); }
/* Friend Classes */ #include <iostream.h> #include<conio.h> class time { int seconds; friend class date; // friend class declared public : void set(int); }; void time::set(int n) { seconds = n; } class date { int day, month, year; public : void set(int, int, int); void print_date(); void print_time(time); }; void date::set(int d, int m, int y) { day = d; month = m; year = y; }
void date::print_date() { cout << "Date : " << day << "/ << month << "/<< year << "\n"; } void date::print_time(time t) { int h = t.seconds / 3600, m = (t.seconds % 3600) / 60; cout << "Time : " << h << ":" << m << "\n"; } void main(void) { clrscr(); date todays_date; time current_time; todays_date.set(16,2,2002); current_time.set(12000); todays_date.print_date(); todays_date.print_time(current_time); getch(); }
/* Friend Functions */ #include <iostream.h> #include<conio.h> class time { int seconds; public : void set(int); friend void print_time(time); // Friend function Declaration }; void time::set(int n) { seconds = n; } void print_time(time dt) // Friend function definition { int h = dt.seconds / 3600, // Friend function can access m = (dt.seconds % 3600) / 60; // private data members cout << "Time : " << h << ":" << m << "\n"; }
/* Friend function- bridge between classes */ #include <iostream.h> #include<conio.h> class date; // declaration to provide the forward reference class time { int seconds; public : void set(int); friend void print_datetime(date,time); }; void time::set(int n) { seconds = n; } class date { int day, month, year; public : void set(int, int, int); friend void print_datetime(date,time); };
void date::set(int d, int m, int y) { day = d; month = m; year = y; } void print_datetime(date d, time t) // Friend function definition { int h = t.seconds / 3600,m = (t.seconds % 3600) / 60; cout << "Date : " <<d.day << "/<<d.month <<"/<<d.year <<"\n"; cout << "Time : << h << ":" << m << "\n"; } void main(void) { clrscr(); date todays_date; time current_time; todays_date.set(16,2,2002); current_time.set(12000); print_datetime(todays_date, current_time); getch(); }
#include <iostream.h> #include <conio.h> class DB; class DM { int meters; float centimeters; public: void getdata() { cout<<"\nEnter Meter : "; cin>>meters; cout<<"\nEnter Centimeter : "; cin>>centimeters; } friend void add(DM dm, DB db, int ch); };
class DB { int feet; float inches; public: void getdata() { cout<<"\nEnter Feet : "; cin>>feet; cout<<"\nEnter Inches : "; cin>>inches; } friend void add(DM dm, DB db, int ch); }; void add(DM dm, DB db, int ch) { if(ch==1) {//Result in meter-centimeter dm.centimeters=dm.centimeters+(db.feet*30)+(db.inches*2.4);
while(dm.centimeters>=100) { dm.meters++; dm.centimeters=dm.centimeters-100; } cout<<"\nMeter : "<<dm.meters; cout<<"\nCentimeters : "<<dm.centimeters; } else if(ch==2) { //Result in feet-inches db.inches=db.inches+(dm.centimeters+dm.meters*100)/2.4; while(db.inches>=12) { db.feet++; db.inches=db.inches-12; } cout<<"\nFeet : "<<db.feet; cout<<"\nInches : "<<db.inches; } else cout<<"\nWrong input!!!"; }
void main() { DM dm; DB db; int ch; int ans=1; do { clrscr(); dm.getdata(); db.getdata(); cout<<"\n1.Meter-Centimeter"; cout<<"\n2.Feet-Inches"; cout<<"\nEnter your choice : "; cin>>ch; add(dm,db,ch); cout<<"\nDo u want to continue?(1/0):"; cin>>ans; } while(ans==1); getch(); }
#include <iostream.h> #include <conio.h> class test2; class test1 { int m1,m2,m3,m4,m5; public: void getdata() { cout<<"\nEnter Marks: "; cin>>m1>>m2>>m3>>m4>>m5; } friend void avg(test1 t1, test2 t2); }; class test2 { int m1,m2,m3,m4,m5; public: void getdata() { cout<<"\nEnter Marks: "; cin>>m1>>m2>>m3>>m4>>m5; } friend void avg(test1 t1, test2 t2); };
void avg(test1 t1, test2 t2) { float tot1,tot2,tot3,tot4,tot5,avg1,avg2,avg3,avg4,avg5; tot1=t1.m1+t2.m1; tot2=t1.m2+t2.m2; tot3=t1.m3+t2.m3; tot4=t1.m4+t2.m4; tot5=t1.m5+t2.m5; avg1=tot1/2; avg2=tot2/2; avg3=tot3/2; avg4=tot4/2; avg5=tot5/2; cout<<"1st test\t2nd test\tAverage\n"; cout<<" "<<t1.m1<<" "<<"\t"<<" "<<t2.m1<<" "<<"\t"<< cout<<" "<<t1.m2<<" "<<"\t"<<" "<<t2.m2<<" "<<"\t"<<" cout<<" "<<t1.m3<<" "<<"\t"<<" "<<t2.m3<<" "<<"\t"<<" cout<<" "<<t1.m4<<" "<<"\t"<<" "<<t2.m4<<" "<<"\t"<<" cout<<" "<<t1.m5<<" "<<"\t"<<" "<<t2.m5<<" "<<"\t"<<" }
void main() { test1 t1; test2 t2; clrscr(); t1.getdata(); t2.getdata(); avg(t1,t2); getch(); }
Static Data Member.: Static data members are data objects that are common to all the objects of a class. They exist only once in all objects of this class. They are already created before the object of the class. Static members are used the information that is commonly accessible. The main advantage of using a static member is to declare the global data which should be updated while the program lives in the memory.
The general syntax of static data member declaration is: Class class_name { private: static data_type variables; static data_type variables; -----------------; }
#include<iostream.h> #include<string.h> #include<conio.h> class sample { private: int x,y; public: void putdata(); }; void sample::putdata() { int sum; sum=x+y; cout<<"X="<<x<<endl; cout<<"Y="<<y<<endl; cout<<"Sum="<<sum<<endl; }
#include<iostream.h> #include<string.h> #include<conio.h> class sample { private: static int x,y; public: void putdata(); }; int sample::x; int sample::y;
void sample::putdata() { int sum; sum=x+y; cout<<"x="<<y<<endl; cout<<"y="<<x<<endl; cout<<"Sum="<<sum; } void main() { clrscr(); sample obj; obj.putdata(); getch(); }
WAP to define a static data member which has the initial value 0 and to find out the sum of the following seriers sum=1+2+3+.+10. the summing of series is to be repeated five times. #include<iostream.h> #include<string.h> #include<conio.h> class series { private: int i,sum; public: void putdata(); };
void series::putdata() { sum=0; for(i=1;i<=10;i++) sum=sum+i; cout<<"sum="<<sum<<endl; } void main() { int i; clrscr(); series obj; for(i=1;i<=5;i++) obj.putdata(); getch(); }
#include<iostream.h> #include<string.h> #include<conio.h> class series { private: int i,sum; public: void putdata(); };
void series::putdata() { for(i=1;i<=10;i++) sum=sum+i; cout<<"sum="<<sum<<endl; } void main() { int i; clrscr(); series obj; for(i=1;i<=5;i++) obj.putdata(); getch(); }
Using Constructor
#include<iostream.h> #include<string.h> #include<conio.h> class series { private: int i,sum; public: series(); void putdata(); }; series::series() { sum=0; }
void series::putdata() { for(i=1;i<=10;i++) sum=sum+i; cout<<"sum="<<sum<<endl; } void main() { int i; clrscr(); series obj; for(i=1;i<=5;i++) obj.putdata(); getch(); }
Using Static #include<iostream.h> #include<string.h> #include<conio.h> class series { private: int i; static int sum; public: void putdata(); }; int series::sum;
void series::putdata() { for(i=1;i<=10;i++) sum=sum+i; cout<<"sum="<<sum<<endl; } void main() { int i; clrscr(); series obj; for(i=1;i<=5;i++) obj.putdata(); getch(); }
The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope. For example:
class X{ public: static int i;}; int X::i = 0; // definition outside class declaration
Once you define a static data member, it exists even though no objects of the static data member's class exist. In the above example, no objects of class X exist even though the static data member X::i has been defined.
#include <iostream> struct X { static const int a = 76;}; const int X::a; int main() { cout << X::a << endl; }
#include <iostream> struct X { private: int i; static int si; public: void set_i(int arg) { i = arg; } static void set_si(int arg) { si = arg; } void print_i() { cout << "Value of i = " << i << endl; cout << "Again, value of i = " << this->i << endl; }
static void print_si() { cout << "Value of si = " << si << endl; // cout << "Again, value of si = " << this->si << endl; }}; int X::si = 77; // Initialize static data member int main() { X xobj; xobj.set_i(11); xobj.print_i(); // static data members and functions belong to the class and can be accessed without using an object of class X. X::print_si(); X::set_si(22); X::print_si(); }
The following is the output of the above example: Value of i = 11 Again, value of i = 11 Value of si = 77 Value of si = 22
#include <iostream> class C { static void f() { cout << "Here is i: " << i << endl; } static int i; int j; public: void printall(); }; void C::printall() { cout << "Here is j: " << this->j << endl; this->f();} int C:: i = 3; int main() { C obj_C(0); obj_C.printall();}
// static_member_functions.cpp #include <stdio.h> class StaticTest { private: static int x; public: static int count() { return x; }}; int StaticTest::x = 9; int main() { printf_s("%d\n", StaticTest::count()); } Output 9
INHERITANCE
Creating or deriving a new class using another class as a base is called inheritance in C++. The new class created is called a Derived class and the old class used as a base is called a Base class in C++ inheritance terminology.
C++ inheritance is very similar to a parent-child relationship. When a class is inherited all the functions and data member are inherited, But there are some exceptions to it too.
Some of the exceptions to be noted in C++ inheritance are as follows. The constructor and destructor of a base class are not inherited the assignment operator is not inherited the friend functions and friend classes of the base class are also not inherited.
Types of inheritance
Single Inheritance
It is a well known fact that the private and protected members are not accessible outside the class. But a derived class is given access to protected members of the base class. General Form of Inheritance: class derived-class_name : access-specifier base_class_name { private: // data members public: // data members // methods protected: // data members };
Example If we define a class computer then it could serve as the base class for defining other classes such as laptops, desktops etc.. This is because as you know that laptops have all the features of computers and so have desktops (and so should their classes) but they have their specific features too. So, rather than defining all the features of such classes from scratch, we make them inherit general features from other classes.
class computer { private: int speed; int main_memory; int harddisk_memory; public: void set_speed(int); void set_mmemory(int); void set_hmemory(int); int get_speed(); int get_mmemory(); int get_hmemory(); };
As you can see, the features (properties and functions) defined in the class computer is common to laptops, desktops etc. so we make their classes inherit the base class computer.
class laptop: public computer { private: int battery_time; float weight; public: void set_battime(int); void set_weight(float); int get_battime(); float get_weight(); };
This way the class laptop has all the features of the base class computer and at the same time has its specific features (battery_time, weight) which are specific to the laptop class. If we didnt use inheritance we would have to define the laptop class something like this:
class laptop { private: int speed; int main_memory; int harddisk_memory; int battery_time; float weight;
public: void set_speed(int); void set_mmemory(int); void set_hmemory(int); int get_speed(); int get_mmemory(); int get_hmemory(); void set_battime(int); void set_weight(float); int get_battime(); float get_weight(); };
And then again we would have to do the same thing for desktops and any other class that would need to inherit from the base class computer. Thanks to inheritance, we dont need to do all this!
// Introduction to Inheritance in C++ // -----------------------// An example program to // demonstrate inheritance in C++ #include<iostream.h> class computer // base class for inheritance { private: float speed; int main_memory; int harddisk_memory;
public: void set_speed(float); void set_mmemory(int); void set_hmemory(int); float get_speed(); int get_mmemory(); int get_hmemory(); }; // -- MEMBER FUNCTIONS -void computer::set_speed(float sp) { speed=sp; } void computer::set_mmemory(int m) { main_memory=m; }
void computer::set_hmemory(int h) { harddisk_memory=h; } int computer::get_hmemory() { return harddisk_memory; } int computer::get_mmemory() { return main_memory; } float computer::get_speed() { return speed; } // -- ENDS --
class laptop: public computer { private: int battery_time; float weight; public: void set_battime(int); void set_weight(float); int get_battime(); float get_weight(); };
// inherited class
// -- MEMBER FUNCTIONS -void laptop::set_battime(int b) { battery_time=b; } void laptop::set_weight(float w) { weight=w; } int laptop::get_battime() { return battery_time; } float laptop::get_weight() { return weight; } // -- ENDS --
void main(void) { computer c; laptop l; c.set_mmemory(512); c.set_hmemory(1024); c.set_speed(3.60); // set common features l.set_mmemory(256); l.set_hmemory(512); l.set_speed(1.8); // set specific features l.set_battime(7); l.set_weight(2.6);
// show details of base class object cout<<"Info. of computer class\n\n"; cout<<"Speed:"<<c.get_speed()<<"\n"; cout<<"Main Memory:"<<c.get_mmemory()<<"\n"; cout<<"Hard Disk Memory: <<c.get_hmemory() <<"\n"; //show details of derived class object cout<<"\n\nInfo. of laptop class\n\n"; cout<<"Speed:"<<l.get_speed()<<"\n"; cout<<"Main Memory:"<<l.get_mmemory()<<"\n"; cout<<"Hard Disk Memory:"<<l.get_hmemory()<<"\n"; cout<<"Weight:"<<l.get_weight()<<"\n"; cout<<"Battery Time:"<<l.get_battime()<<"\n"; }
output
Info. of computer class Speed:3.6 Main Memory:512 Hard Disk Memory:1024
Info. of laptop class Speed:1.8 Main Memory:256 Hard Disk Memory:512 Weight:2.6 Battery Time:7
Single Inheritance
In "single inheritance," a common form of inheritance, classes have only one base class. Consider the relationship illustrated in the fig. Simple SingleInheritance Graph
Note: The derived class has a "kind of" relationship with the base class. In the figure, a Book is a kind of a PrintedDocument, and a PaperbackBook is a kind of a book.
--------------------------------------- }; // baseB is a direct Class baseB { base class --------------------------------------- }; Class derivedC : public baseA, public baseB { ----------------------------------------- };
Indirect Base Class: A Class is called as an indirect base class if it is not a direct base , but is a base class of one of the classes mentioned in the base list. E.g.
Class baseA { // baseA is a direct base class --------------------------------------- }; Class derivedB : public baseA { ----------------------------------------- }; Class derivedC : public derivedB { ----------------------------------------- }; // indirect base
Develop an object oriented program in C++ to read the following information from the keyboard in which the base class consists of: employee name, code and designation. The derived class contains the data members viz. years of experience and age.
Types of Derivation
A derived class can be defined with one of the access specifiers, i.e 1.Public Inheritance 2.Private Inheritance 3.Protected Inheritance
Public Inheritance:
The most important type of access specifier is public. In public derivation Each public member in the base class is public in the derived class. Each protected member in the base class is protected in the derived class. Each private member in the base class remains private in the base class & not inherited in the derive class.
Private Inheritance:
In private derivation Each public member in the base class is private in the derived class. Each protected member in the base class is private in the derived class. Each private member in the base class remains private in the base class & hence it is not visible in the derive class.
Protected Inheritance:
In protected derivation Each public member in the base class is protected in the derived class. Each protected member in the base class is protected in the derived class. Each private member in the base class remains private in the base class & hence it is not visible in the derive class.
Write a program in C++ which will print the sum and average of n numbers using inheritance; void sumavg:: getdata() #include<iostream.h> { class sumavg cout<<"enter the value for n"<<endl; { cin>>n; private: for(i=0;i<n;i++) int n; cin>>m[i]; public: } int i; int sumavg:: getn() float m[100]; { void getdata(); return(n); int getn(); } }; float x1:: sum() class x1: public sumavg { s=0; { for(i=0;i<n;i++) private: { float s,av; s=s+m[i]; public: } float sum(); return(s); float avg(); }; void putdata(); };
float x1:: avg() { av=sum()/getn(); return(av); } void x1::putdata() { cout<<"n="<<getn()<<endl; cout<<"Sum="<<s<<endl; cout<<"Average="<<av<<endl;; } int main() { x1 ob; ob.getdata(); ob.sum(); ob.avg(); ob.putdata(); return 0; }
Write a program to implement single inheritance from following figure. Accept and display data for one table.
Class_Furniture Data members: material,price Class_table Data members: height,surface_area
#include<iostream.h> #include<conio.h> class furniture { protected: char material[10]; float price; public: void get_data() { cout<<"\nEnter the name of the material for furniture\n"; cin>>material; cout<<"\nEnter the price\n"; cin>>price; } void put_data() { cout<<"\nMaterial name for furniture==>\t"<<material<<endl; cout<<"\nPrice of furniture==>\t"<<price<<endl; } };
class table:public furniture { protected: float height,surface_area; public: void get_tab() { cout<<"\nEnter the height of the table\n"; cin>>height; cout<<"\nEnter the surface area of the table\n"; cin>>surface_area; } void put_tab() { cout<<"\nThe height of the table==>\t"<<height<<endl; cout<<"\nThe surface area of the table==>\t"<<surface_area<<endl; } };
void main() { clrscr(); table s; s.get_data(); s.get_tab(); cout<<"\n*********************************\n"; s.put_data(); s.put_tab(); getch(); }
Write a program to implement multi level inheritance from following figure. Accept and display data for one student. Class student
Data members: rollno, name
#include<iostream.h> #include<conio.h> class Student { private: int roll_no; char *name; public: void getdata() { cout<<"Enter roll_no"<<endl; cin>>roll_no; cout<<"Enter the name of the student"<<endl; cin>>name; } void putdata() { cout<<"\nROLL_NO==>"<<roll_no; cout<<"\nNAME OF THE STUDENT==>"<<name; } };
class Test:public Student { protected: int m1,m2,m3,m4,m5; public: void getmks() { cout<<"Enter the marks for five subjects==>"<<endl; cin>>m1>>m2>>m3>>m4>>m5; } }; class Result:public Test { int total; public: void gettot() { total=m1+m2+m3+m4+m5; }
void putt() { cout<<"\nMARKS FOR FIRST SUBJECT="<<m1; cout<<"\nMARKS FOR SECOND SUBJECT="<<m2; cout<<"\nMARKS FOR THIRD SUBJECT="<<m3; cout<<"\nMARKS FOR FOURTH SUBJECT="<<m4; cout<<"\nMARKS FOR FIFTH SUBJECT="<<m5; cout<<"\nTOTAL="<<total; } }; void main() { clrscr(); Result r; r.getdata(); r.getmks(); r.gettot(); r.putdata(); r.putt(); getch(); }
Write a program to implement single inheritance from following figure. Accept and display products flavors only with sweet.
Class product Data members: product_id, name
#include<iostream.h> #include<conio.h> #include<string.h> class product { public: int product_id; char name[20]; };
class edible: public product { public: float weight; float price; char flavor[15]; void getdata() { cout<<"\n\nEnter the product id"; cin>>product_id; cout<<"\n\nEnter the name of the product"; cin>>name; cout<<"\n\nEnter the weight of product"; cin>>weight; cout<<"\n\nEnter the price"; cin>>price; cout<<"\n\nEnter the flavor (Either sweet or sour)"; cin>>flavor; }
void main() { clrscr(); edible a[4]; for(int i=0;i<4;i++) a[i].getdata(); for(i=0;i<4;i++) { if(strcmpi(a[i].flavor,"sweet")==0) a[i].putdata(); } getch(); }
Write a program to implement multi level inheritance from following figure. Where sell_price is price plus 1.5% VAT. Accept and display data for one medicine.
Class medicine Data members: company, name
Class dealer Data members: product_name,price Class retailer Data member: sell_price
Class A { --------------------------------------};
// grandparent class
Class B : virtual public A // parent 1 class { ----------------------------------------}; Class C : public virtual A // parent 2 class { ----------------------------------------}; Class D : public virtual A // child class { ----------------------------------------}; Note: keyword Virtual and public may be used in either order.
Write a program to implement multiple inheritance from the following figure. Accept and display data of student and teacher for one object of class info.
Class student Data members: rollno, name Class teacher Data members: name, subject
Class info
Data member: branch
#include<iostream.h> #include<conio.h> class Student { public: int roll_no; char name[20]; void getin() { cout<<"\n Enter the roll no of student"; cin>>roll_no; cout<<"\n Enter the name of student"; cin>>name; } void putout() { cout<<"\n Roll number of student is:\n"<<roll_no; cout<<"\n Name of student is:"<<name; } };
class Teacher { protected: char name[20]; char subject[20]; public: void get() { cout<<"\n Enter the name of teacher\n"; cin>>name; cout<<"\n Enter the name of subject\n"; cin>>subject; } void put() { cout<<"\n Name of teacher is:"<<name; cout<<"\n Name of subject is:"<<subject; } };
class Info:public Student, public Teacher { protected: int branch; public: void input() { cout<<"\n Enter branch "; cin>>branch; } void show() { cout<<" \n Branch is:"<<branch; } };
void main() { clrscr(); Info I; I.getin(); I.get(); I.input(); I.putout(); I.put(); I.show(); getch(); }
Write a program to implement multiple inheritance from the following figure. Accept and display data of shape and calculate its area.
Class triangle Data members: base,height gettri(); Class rectangle Data members: l, b getrec()
Here the class D inherit all the public and protected members of class A twice, first via class B and second via. Class C & thus child would have duplicate sets of the members inherited from class A. This duplication can be avoided by making the common base class as the virtual base class.
/* Program to illustrates Virtual base class */ #include<iostream.h> #include<conio.h> class student { protected : int roll_number; public: void get_number(int a) { roll_number = a; } void put_number(void) { cout<<"Roll No. : "<<roll_number<<endl; } }; class test : virtual public student { protected : float sem1, sem2; public:
void get_marks (float s1, float s2) { sem1 = s1 ; sem2 = s2; } void put_marks(d) { cout<<"Marks obtained : "<<"\n <<"Sem1 = " <<sem1<<"\n <<"Sem2 = " <<sem2<<"\n; } }; class sports : public virtual student { protected : float score; public: void get_score(float s) { score = s; } void put_score() { cout<<" Sports weight : "<<score<<"\n\n"; };
class result : public test, public sports { float total; public : void display(); }; void result :: display () { total = sem1 + sem2 + score; put_number( ); put_marks( ); put_score( ); cout<<"Total Marks : "<<total<<"\n"; }
Class B: public A A( ); base constructor { B( );derived constructor }; Class A: public B, public C B( ); base (first) { C( ); base (second) }; A( ); derived Class A: public B, virtual public C C( ); Virtual base { B( ); ordinary base }; A( ); derived
#include<iostream.h> #include<conio.h> class A { public: A() { cout<<"Class A constructor is generated\n"; } void showA() { cout<<"Class A \n"; } };
class B { public: B() { cout<<"Class B constructor is generated\n"; } void showB() { cout<<"Class B \n"; } };
class C: public A,public B { public: C( ) { cout<<"Class C constructor is generated\n"; } void showC() { cout<<"Class C \n"; } };
void main() { clrscr(); C obj; cout<< "******\n"; obj.showC(); obj.showB(); obj.showA(); getch(); }
OUTPUT: Class A constructor is generated Class B constructor is generated Class C constructor is generated ****************** Class C Class B Class A
Pointer to array
WAP in C++ which will print the entire array using pointer to array with function.
#include<iostream.h> #include<conio.h> void display(int *,int); void main() { int a[100],n; cout<<"enter the size of an array\n"; cin>>n; display(a,n); getch(); } void display(int *ptr,int n) { int i; for(i=0;i<n;i++) { cin>>*(ptr+i); } for(i=0;i<n;i++) { cout<<*(ptr+i)<<endl; } }
enter the size of an array 5 Enter the data for the array 231 45 12 789 34 Entire Array 231 45 12 789 34
WAP in C++ which will print the entire array in an ascending order by using pointer to array.
#include<iostream.h> #include<conio.h> void main() { int *ptr,i,j,t,a[100],n; cout<<"enter the size of an array\n"; cin>>n; cout<<"Pls. enter the data for an array\n"; for(i=0;i<n;i++) { cin>>*(ptr+i); }
for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(*(ptr+i)>*(ptr+j)) { int t=*(ptr+i); *(ptr+i)=*(ptr+j); *(ptr+j)=t; } } } cout<<"Array in ascending order\n"; for(i=0;i<n;i++) { cout<<*(ptr+i)<<endl; } getch(); }
enter the size of an array 5 Pls. enter the data for an array 34 12 4 67 21 Array in ascending order 4 12 21 34 67
Pointer to string
Syntax : Data_type *pointer_variable name; Eg: char *ptr; To inotialize pointer to the base address of string, we can assign pointer to the name of the string or to the address of the first element of string. For e.g ptr=str; or ptr=str[0];
WAP in c++ to find the length of a string using pointer. #include<iostream.h> #include<string.h> #include<conio.h> void main() { char *str; int l; cout<<"enter any string \n"; cin>>str; l=strlen(str); cout<<"length="<<l; getch(); }
#include<iostream.h> #include<conio.h> void main() { char *p,*str; int l; cout<<"enter any string \n"; cin>>str; l=0; p=str; while(*p!='\0') { l=l+1; p=p+1; } cout<<"length="<<l; getch(); }
WAP in c++ to accept string from user and count the no of vowels in the string using pointer to string. #include<iostream.h> #include<conio.h> #include<ctype.h> char *str,*s; int count=0; void main() { clrscr(); cout<<"\n\t\tEnter the string:-\t"; cin>>str; s=str;
/***PROGRAM TO PRINT REVERSE OF ANY STRING***/ #include<iostream.h> #include<conio.h> void main() { char str[30],str1[30],*p,*q; cout<<"Enter any string\n"; cin>>str; p=str; q=strl; int l=0; while(*p!=0) { l++; p++; } *q='0'; p=p-1; cout<<"\nString before reverse ::\t"<<str<<endL; while(1!=0) cout<<"\nString after reverse ::\t"<<str<<endL; { *q=*p; getch(); q++; } p--; l--; } OUTPUT
Enter the string:HELLO The reverse is:OLLEH
/***PROGRAM TO COPY ONE STRING TO ANOTHER ***/ #include<iostream.h> #include<conio.h> void main() { char str1[40],str[40],*p,*q; cout<<"Please enter first string\n"; cin>>str1; cout<<"Please enter second string\n"; cin>>str2; while(*q!='0') p=str1; { *p=*q; q=str2; p++; while(*p!='0') q++; { }*p='\0' p++; cout<<"New string after copied } ::\t"<<str1; getch(); }
/***PROGRAM TO Concat ONE STRING TO ANOTHER ***/ #include<iostream.h> #include<conio.h> void main() { char str1[40],str[40],*p,*q; cout<<"Please enter first string\n"; cin>>str1; cout<<"Please enter second string\n"; cin>>str2; while(*q!='0') p=str1; { *p=*q; q=str2; p++; while(*p!='0') q++; { }*p='\0' p++; cout<<"New string after copied } ::\t"<<str1; getch();}
Pointers to objects Pointer to object is a pointer variable of the same class whose object is to be pointed to by it. Syntax: Class_name *variable_name To access individual members of objects using pointer, an operator called arrow(->) (formed by combination of dash and greater than sign) is used instead of (.) dot operator.
Write a program to declare a class Product having data member as product_name and product_price. Accept and display this data for one object using pointer to the object.
#include<iostream.h> #include<conio.h> class product { private: char product_name[15]; float product_price; public: void getdata() { cout<<"Enter the product name & product price\n"; cin>>product_name>>product_price; }
void putdata() { cout<<"Product_name :"<<product_name<<endl; cout<<"Product price:"<<product_price; } }; void main() { clrscr(); product pp,*p; p=&pp; p->getdata(); p->putdata(); getch(); }
#include<iostream.h> #include<conio.h> class book { char book_title[20]; char author_name[20]; float price; public: void getdata() { cout<<"Enter the Title of the book"<<endl; cin>>book_title; cout<<"Enter the Name of the Author"<<endl; cin>>author_name; cout<<"Enter the Price of the book"<<endl; cin>>price; }
void putdata() { cout<<"****************************************\n"; cout<<"\nTitle of the book::"<<book_title<<endl; cout<<"Name of the Author::"<<author_name<<endl; cout<<"Price of the book::"<<price<<endl; cout<<"\n**************************************"; } }; void main() { clrscr(); book bk,*b; b=& bk; b->getdata(); b->putdata(); getch(); }
Output: Enter the Title of the book C++ Enter the Name of the Author Balagurusami Enter the Price of the book 350 **************************************** Title of the book::C++ Name of the Author::Balagurusami Price of the book::350 **************************************
#include<iostream.h> #include<conio.h> class box { float height; float width; float breadth; public: void getdata() { cout<<"Enter the Height of the Box"<<endl; cin>>height; cout<<"Enter the Width of the Box"<<endl; cin>>width; cout<<"Enter the Breadth of the Box"<<endl; cin>>breadth; }
void cal() { float area,volume; area=(2*height*breadth)+(2*height*width)+(2*breadth*width); volume=height*width*breadth; cout<<"Area of Box::"<<area<<endl; cout<<"Volume of Box::"<<volume<<endl; cout<<"\n********************************************\n"; } void putdata() { cout<<"\n******************************************\n\n"; cout<<"Height of the Box::"<<height<<endl; cout<<"Width of the Box::"<<width<<endl; cout<<"Breadth of the Box::"<<breadth<<endl; }
void main() { clrscr(); box bx,*b; b=& bx; b->getdata(); b->cal(); b->putdata(); getch(); }
Output: Enter the Height of the Box 2 Enter the Width of the Box 2 Enter the Breadth of the Box 2 ****************************************** Height of the Box::2 Width of the Box::2 Breadth of the Box::2 Area of Box::24 Volume of Box::8 ********************************************
#include<iostream.h> #include<conio.h> class birthday { int day,year; char month[20]; public: void getdata(); void putdata(); }a[5]; void birthday::getdata() { for(int i=0;i<5;i++) { cout<<"Enter the Day,Month and Year"<<endl; cin>>a[i].day>>a[i].month>>a[i].year; } }
void birthday::putdata() { cout<<"\n*****************************************\n\n"; cout<<"\tDay\t"; cout<<"Month\t"; cout<<"Year\n\n"; for(int i=0;i<5;i++) { cout<<"\t"<<a[i].day<<"\t"<<a[i].month<<"\t"<<a[i].year<<endl; } cout<<"\n******************************************\n\n"; } void main() { clrscr(); birthday birth,*b; b=& birth; b->getdata(); b->putdata(); getch(); }
Enter the Day,Month and Year 12 3 1985 Enter the Day,Month and Year 25 7 1998 Enter the Day,Month and Year 23 7 1980 Enter the Day,Month and Year 31 12 2000 Enter the Day,Month and Year 4 4 2004 ***************************************** Day Month Year 12 3 1985 25 7 1998 23 7 1980 31 12 2000 4 4 2004 ******************************************
#include<iostream.h> #include<conio.h> #include<string.h> class employee { int emp_id; char emp_name[15],dept[15]; public: void get(); void put(); }e[5]; void employee::get() { for(int i=0;i<5;i++) { cout<<"Enter the ID, Name & dept. of the employee\n"; cin>>e[i].emp_id>>e[i].emp_name>>e[i].dept; } }
void employee::put() { for(int i=0;i<5;i++) { if(strcmpi(e[i].dept,"computer")==0) { cout<<"*********************************\n"; cout<<"Emp_ID:-\t"<<e[i].emp_id<<endl; cout<<"Emp_Name:-\t"<<e[i].emp_name<<endl; cout<<"Depatment:-\t"<<e[i].dept<<endl; cout<<"**********************************\n"; }}
void main() { clrscr(); Employee em,*e; e=& em; e->get(); e->put(); getch(); }
Enter the ID, Name & dept. of the employee 1 Sameer Computer Enter the ID, Name & dept. of the employee 2 Rajesh Computer Enter the ID, Name & dept. of the employee 3 Faizan Infotech Enter the ID, Name & dept. of the employee 4 Pramod Computer Enter the ID, Name & dept. of the employee 5 Saify Infotech
********************************* Emp_ID:1 Emp_Name:Sameer Depatment:- Computer ********************************** ********************************* Emp_ID:2 Emp_Name:Rajesh Depatment:- Computer ********************************** ********************************* Emp_ID:4 Emp_Name:Pramod Depatment:- Computer **********************************
This Pointers A Pointer is a variable which holds address. This pointer is a variable which is used to access the address of the class itself To access individual members of objects using This pointer, an operator called arrow (->) (formed by combination of dash and greater than sign) is used instead of (.) dot operator.
// program to illustrate 'this'pointer #include<iostream.h> #include<conio.h> class myclass { int a; public: myclass(int); void show(); }; myclass::myclass(int x) { // same as writing a=10 this->a=x; };
void myclass::show() { // same as writing cout<<a; cout<<"Value of a="<<this->a; } void main() This Pointer: Output Value of a=10 { clrscr(); myclass ob(10); ob.show(); getch(); }
#include<iostream.h> #include<conio.h> class test { private: int id; char name[30]; public: void getdata(); void putdata(); }; void test::getdata() { cout<<"input for current object\n"; cin>>id; cin>>name; } void test::putdata() { cout<<"output for current object\n"; cout<<"Id="<<this->id<<endl; cout<<"name="<<this->name; }
void main() { clrscr(); test t1,t2; t1.getdata(); t1.putdata(); t2.getdata(); t2.putdata(); getch(); }
/* Program to illustrates this pointer */ void main( ) #include<iostream.h> { #include<conio.h> example e1; class example e1.setdata(10); { private : e1.showdata( ); int i; getch( ); public : } void setdata(int ii) { i = ii; //one way to set data cout<<endl<<" My object's address is "<<this << endl; this->i=ii; // another way to set data } void showdata( ) { cout<<i; // one way to display data cout<<endl<<" My object's address is "<<this<< endl; cout<<this->i; //another way to display data } };
It is overloading of operators operating on single operand. There should be no argument to the operator function.
BINARY OPERATOR OVERLOADING:
It is overloading of operator operating on two operands. There should be one parameter to the operator function.
:: , sizeof , ?: , .*, .
Syntax:
The syntax for the operator function declaration within the scope.
Return_data_type operator[op] (parameter_list) { ------------------------------------------------} Syntax: //Function body.
Void sample::operator () { a=-a; b=-b; } Void sample::print() { cout << a=<<a<<endl; cout << b=<<b<<endl; } Void main() { sample obj(10,20); cout<<Before the operator unary minus\n; obj.print(); -obj; // OR obj.operator () Cout<<After the operator unary minus\n; obj.print(); }
#include<iostream.h> #include<conio.h> class test { private: int x,y,z; public: void getdata() { cout<<"Pls. enter any three values\n"; cin>>x>>y>>z; } void putdata() { cout<<x<<endl<<y<<endl<<z<<endl; }
void operator ++() { x++; y++; z++; } }; void main() { clrscr(); test obj; obj.getdata(); cout<<"before operator overloading the values are\n"; obj.putdata(); obj++; cout<<"After operator overloading the values are\n"; obj.putdata(); getch(); }
Output: Pls. enter any three values 10 20 30 before operator overloading the values are 10 20 30 After operator overloading the values are 11 21 31
#include<iostream.h> #include<conio.h> class distance { float x,y,z; public: void feet() { cout<<"\n Enter the distance in feets\n"; cin>>x>>y>>z; cout<<"\n Distance in feets are==>"; cout<<"\n x-->"<<x<<"\n y-->"<<y<<"\n z-->"<<z; } void inches() { cout<<"\n Distance in inches\n"; x=x*12; y=y*12; z=z*12; cout<<"\n x:"<<x<<"\n y:"<<y<<"\n z:"<<z; }
void operator--() { x--; y--; z--; } void display() { cout<<"\n Decrement in inches are as follows:-\n"; cout<<"\n x==>"<<x<<"\n y==>"<<y<<"\n z==>"<<z; } }; void main() { clrscr(); distance d; d.feet(); d.inches(); d--; d.display(); getch(); }
Enter the distance in feets 120 100 12 Distance in feets are==> x-->120 y-->100 z-->12 Distance in inches x:1440 y:1200 z:144 Decrement in inches are as follows:x==>1439 y==>1199 z==>143
#include<iostream.h> #include<conio.h> #include<string.h> class con { char str1[10],*str2; public : void get() { cout<<"Enter a Strings\n"; cin>>str1; cin>>str2; } void operator +(con) { strcat(str1,str2); cout<<"\n\n**********"; cout<<"\n\n\n"<<str1; } };
#include<iostream.h> #include<conio.h> #include<string.h> class con { char str1[10],*str2; public : void get() { cout<<"Enter a Strings\n"; cin>>str1; cin>>str2; }
void operator +(con) { strcat(str1,str2); cout<<"\n\n**********"; cout<<"\n\n\n"<<str1; } }; void main() { clrscr(); con c1; c1.get(); c1+c1; getch(); }
#include<iostream.h> #include<conio.h> #include<string.h> class string { char *string1; char *string2; public: void get_string() { cout<<"\n enter the first string \n"; cin>>string1; cout<<"\n enter the second string\n"; cin>>string2; }
void operator==(string) { if(strcmp(string1,string2)==0) cout<<"The strings are equal"; else cout<<"The strings are not equal"; } }; void main() { clrscr(); string s; s.get_string(); s==s; getch(); }
OUTPUT enter the first string IT enter the second string CO The strings are not equal
#include<iostream.h> #include<conio.h> class neg { int x,y,z; public: void get() { cout<<"enter value of x y z\n"; cin>>x>>y>>z; } void operator --() { x--; y--; z--; }
void display() { cout<<"\nx:"<<x; cout<<"\ny:"<<y; cout<<"\nz:"<<z; } }; void main() { clrscr(); neg n; n.get(); n.display(); n--; cout<<"\n\n\n"; n.display(); getch(); }
#include<iostream.h> #include<conio.h> #include<string.h> class string { char *str1,*str2; public: void get() { cout<<"Enter 2 strings to compare the length\n"; cin>>str1>>str2; }
void operator >(string) { if(strlen(str1)>strlen(str2)) cout<<"string1 > string2"; else { if(strlen(str1)==strlen(str2)) cout<<"string1 = string2"; else cout<<"string2 > string1"; } } } }; void main() { clrscr(); string s; s.get(); s>s; getch(); }
OUTPUT Enter 2 strings to compare the length COMPUTER MECHANICAL string2 > string1
WAP to declare a class distance to hold distance in feet and inches. Overload unary minus operator so that values of feet and inches of object will be negated. (use this pointer in operator function.)
#include<iostream.h> #include<conio.h> class distance { int inch,feet; public: void getdata() { cout<<"Enter the distance in feets==>\t"; cin>>feet; cout<<"\nEnter the distance in inches==>\t"; cin>>inch; }
void operator-() { feet=-feet; inch=-inch; cout<<"\n\n********************************\n\n"; cout<<"\nValues after negation\n"; cout<<"\nfeets==>\t"<<this->feet<<endl; cout<<"\ninches==>\t"<<this->inch<<endl; } void putdata() { cout<<"\nDistance in feets==>\t"<<feet<<endl; cout<<"\nDistance in inches==>\t"<<inch<<endl; } };
********************************
WAP to declare a class student having data members roll_no and percentage. Using this pointer invoke member function to accept and display this data for one objct of the class.
#include<iostream.h> #include<conio.h> class student { int roll_no; float per; public: student(int r,float p) { roll_no=r; per=p; }
void display() { cout<<"\n\n\t***********\tStudent Information\t*************\n"; cout<<"\n\nRoll no="<<this->roll_no; cout<<"\n\nPercentage="<<this->per<<"%"; } }; void main() { clrscr(); student s(5,78); s.display(); getch(); }
*********** Student Information Roll no=5 Percentage=78% *************
Function Overriding
What is overriding
Answer : To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list. The definition of the method/function overriding is: Must have same method name. Must have same data type. Must have same argument list. Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class.
What is difference between overloading and overriding? Answer : a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.
POLYMORPHISM
Polymorphism: Poly means many & morphs means forms. It simply means one name multiple forms.
Polymorphism
Function Overloading
Operator Overloading
The selection of a particular function definition for a particular function call of a overloaded function at compile time by the compiler is called as early binding or static binding. The same is true for operator overloading. Therefore function overloading or operator overloading is know as compile time polymorphism or also known as ad-hoc polymorphism.
In run time polymorphism the member function could be selected while is program is running is known as run time polymorphism. Run time polymorphism called address of the function at run time, which is known as late binding or dynamic binding.
Virtual Function
A virtual function is a member function that can be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function. Virtual functions ensure that the correct function is called for an object, regardless of the expression used to make the function call.
Suppose a base class contains a function declared as virtual and a derived class defines the same function. The function from the derived class is invoked for objects of the derived class, even if it is called using a pointer or reference to the base class. For example
#include<iostream.h> #include<conio.h> class Base { public: void who() { // specify without a virtual function cout << "Base\n"; } }; class derived1 : public Base { public: void who() { // redefine who() for DerivedClass1 cout << "First derivation\n"; } }; class derived2 : public Base { public: void who() { // redefine who() for DerivedClass2 cout << "Second derivation\n"; } };
int main() { OUTPUT: clrscr(); Base Base b,*p; Base Base derived1 d1; derived2 d2; p = &b; p->who(); // access BaseClass's who p = &d1; p->who(); // access DerivedClass1's who p = &d2; p->who(); // access DerivedClass2's who getch(); return 0; }
#include<iostream.h> #include<conio.h> class Base { public: virtual void who() { // specify a virtual function cout << "Base\n"; } }; class derived1 : public Base { public: void who() { // redefine who() for DerivedClass1 cout << "First derivation\n"; } }; class derived2 : public Base { public: void who() { // redefine who() for DerivedClass2 cout << "Second derivation\n"; } };
int main() { clrscr(); Base b,*p; derived1 d1; derived2 d2; p = &b; p->who(); // access BaseClass's who p = &d1; p->who(); // access DerivedClass1's who p = &d2; p->who(); // access DerivedClass2's who getch(); return 0; } OUTPUT: Base First derivation Second derivation
#include<iostream.h> #include<conio.h> class Base { public: void who() { // specify a virtual function cout << "Base\n"; } }; class derived1 : public Base { public: void who() { // redefine who() for DerivedClass1 cout << "First derivation\n"; } }; class derived2 : public Base { public: void who() { // redefine who() for DerivedClass2 cout << "Second derivation\n"; } };
int main() { clrscr(); Base b; derived1 d1; derived2 d2; b.who(); // access BaseClass's who d1.who(); // access DerivedClass1's who d2.who(); // access DerivedClass2's who getch(); return 0; }
OUTPUT: Base First derivation Second derivation
#include<iostream.h> #include<conio.h> class employee { public: virtual void display() { cout<<"Base class\n"; } }; class programmer:public employee { public: void display() { cout<<"\n\t\tProgrammer class function called\n"; } };
class manager:public employee { public: void display() { cout<<"\n\t\tManager class function called\n"; } }; void main() { clrscr(); programmer p; manager m; OUTPUT employee *ptr1; ptr1=&p; Programmer class function called ptr1->display(); Manager class function called ptr1=&m; ptr1->display(); getch(); }
#include<iostream.h> #include<conio.h> class shape { public: virtual int display_area() { } }; class triangle:public shape { int x,y,a; public: int display_area() { cout<<"\n\n\tEnter base and height of triangle\n\n"; cin>>x>>y; a=0.5*x*y; cout<<"Area="<<a; } };
class rectangle:public shape { int x,y,a; public: int display_area() { cout<<"\n\n\tEnter length and breadth of rectangle\n\n"; cin>>x>>y; arear=x*y; cout<<"Area="<<a; } }; OUTPUT void main() Enter base and height of triangle { clrscr(); 12 triangle t; 23 rectangle r; Area=138 shape *ptr; Enter length and breadth of rectangle ptr=&t; 32 ptr->display_area(); 7 ptr=&r; Area=224 ptr->display_area(); getch(); }
Abstract Class An abstract class is one that is not used to create objects. An abstract class is design only to act as a base class (i.e. it can be used only for inherited purpose by other classes.
#include using namespace std; class area { double dim1, dim2; public: void setarea(double d1, double d2) { dim1 = d1; dim2 = d2; } void getdim(double &d1, double &d2) { d1 = dim1; d2 = dim2; } virtual double getarea() = 0; // pure virtual function };
class rectangle : public area { public: double getarea() { double d1, d2; getdim(d1, d2); return d1 * d2; } }; class triangle : public area { public: double getarea() { double d1, d2; getdim(d1, d2); return 0.5 * d1 * d2; } };
int main() { area *p; rectangle r; triangle t; r.setarea(3.3, 4.5); t.setarea(4.0, 5.0); p = &r; cout << "Rectangle has area: " << p->getarea() << '\n'; p = &t; cout << "Triangle has area: " << p->getarea() << '\n'; return 0; }