Friday 29 April 2016

Friend Function Example.

#include<iostream.h>
#include<conio.h>
class square
{
int no;
public:
void accept()
{
cout<<"Enter no for square:";
cin>>no;
}
friend void sq(square s);
};
void sq(square s)
{
int ans;
ans=s.no*s.no;
cout<<"Square="<<ans;
}
void main()
{
clrscr();
square s;
s.accept();
sq(s);
getch();
}
/*Output:
Enter no for square:4
Square=16 */

WAP for finding out the weight on any planet using static data member

#include<iostream.h>
#include<conio.h>
class planets
{
static float g;
float w,m;
int ch;
public:
void accept()
{
cout<<"Find weight on:"<<endl;
cout<<"1:MERCURY\n2:VENUS\n3:EARTH\n4:MARS\n5:JUPITER\n6:SATURN\n7:URANUS\n8:NEPTUNE"<<endl;
cout<<"Enter your choice:"<<endl;
cin>>ch;
switch(ch)
{
case 1:
g=3.61;
break;
case 2:
g=8.83;
break;
case 3:
g=9.8;
break;
case 4:
g=3.75;
break;
case 5:
g=26.0;
break;
case 6:
g=11.2;
break;
case 7:
g=10.5;
break;
case 8:
g=13.3;
break;
}
cout<<"Enter mass:";
cin>>m;
}
void display()
{
w=m*g;
cout<<"Weight="<<w;
}
};
float planets::g;
void main()
{
clrscr();
planets p;
p.accept();
p.display();
getch();
}
/*Output:
Find weight on:
1:MERCURY                                                                      
2:VENUS                                                                        
3:EARTH                                                                        
4:MARS                                                                        
5:JUPITER                                                                      
6:SATURN                                                                      
7:URANUS                                                                      
8:NEPTUNE                                                                      
Enter your choice:                                                            
3
Enter mass:10
Weight=98  */

Class with Static Data Member

#include<iostream.h>
#include<conio.h>
class account
{
static int r;
int p,n,si;
public:
void accept()
{
cout<<"Enter Principal amount & No. of years:"<<endl;
cin>>p>>n;
}
void display()
{
si=(p*n*r)/100;
cout<<"Simple Interest="<<si;
}
};
int account::r=10;
void main()
{
clrscr();
account a;
a.accept();
a.display();
getch();
}
/*Output:
Enter Principal amount & No. of years:
500 2                                                                          
Simple Interest=100 */

Thursday 28 April 2016

Another example for inheritance

#include <iostream>
 
using namespace std;

// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};

// Derived class
class Rectangle: public Shape
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
};

int main(void)
{
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   return 0;
}

Modern C++

Write a program showing Friend Function

 #include<iostream.h>
 #include<conio.h>
 class b;
 class a
 {
int no1;
public:
void accept()
{
cout<<"Enter no 1:";
cin>>no1;
}
void display()
{
cout<<"No 1 is greater";
}
friend void great(a,b);
 };
 class b
 {
int no2;
public:
void accept()
{
cout<<"Enter no 2:";
cin>>no2;
}
void display()
{
cout<<"No 2 is greater";
}
friend void great(a,b);
 };
 void great(a m,b n)
 {
if(m.no1>n.no2)
{
m.display();
}
else
{
n.display();
}
 }
 void main()
 {
clrscr();
a m;
b n;
m.accept();
n.accept();
great(m,n);
getch();
}
/*Output:
Enter no 1:23
Enter no 2:21                                                                  
No 1 is greater */

Inheritance Visibily Modes

Single Inheritance

#include<iostream.h>
#include<conio.h>
class employee
{
protected:
int emp_id;
char emp_name[20];
public:
void accept()
{
cout<<"Enter name and emp id=";
cin>>emp_name>>emp_id;
}
void display()
{
cout<<"Name="<<emp_name<<endl;
cout<<"ID="<<emp_id<<endl;
}
};
class worker:public employee
{
protected:
int salary;
public:
void accept1()
{
cout<<"Enter Salary=";
cin>>salary;
}
void display1()
{
cout<<"Salary:"<<salary<<endl;
}
};

void main()
{
clrscr();
worker w;
w.accept();
w.accept1();
w.display();
w.display1();
getch();
}
/*Output:
Enter name and emp id=qqq 123
Enter Salary=200                                                              
Name=qqq                                                                      
ID=123                                                                        
Salary:200                                                                    
*/
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               
                                                                               




What is Inheritance?

Inheritance is a mechanism of deriving a new class form the existing old class.
The old class is referred as base class and new class is referred as the derived class.

New classes inherit some of the properties and behavior of the existing classes. An existing class that is "parent" of a new class is called a base class. New class that inherits properties of the base class is called a derived class.

So basically Inheritance is a technique of code reuse.

Please comment for any program related to Inheritance.

Array Of Objects With Conditions

#include<iostream.h>
#include<conio.h>
class city
{
int pop;
char name[20];
public:
void accept()
{
cout<<"enter name and population"<<endl;
cin>>name>>pop;
}
void display();
}c[5];
void city::display()
{
int max=0,i;
for(i=0;i<5;i++)
{
if(max<c[i].pop)
max=c[i].pop;
}
for(i=0;i<5;i++)
{
if(max==c[i].pop)
{
cout<<"Max Populated city="<<c[i].name<<endl;
cout<<"Population="<<max;
}
}
}
void main()
{
int i;
clrscr();
for(i=0;i<5;i++)
{
c[i].accept();
}
c[i].display();
getch();
}
/*Output:
enter name and population
qqq 123                                                                      
enter name and population
ddd 456
enter name and population
ttt 677
enter name and population
uuu 876
enter name and population
ttg 667
Max Populated city=uuu
Population=876 */

Wednesday 27 April 2016

What is Array Of Objects

Like, Array is a collection of variables of same data type, Similarly the Array Of Objects are the collection of objects of same class type.

Arrays of variables of type "class" is known as "Array of objects". The "identifier" used to refer the array of objects is an user defined data type.

Example:



#include <iostream.h>
const int MAX =100;
class Details
{
private:
int salary;
float roll;
public:
void getname( )
{
cout << "\n Enter the Salary:";
cin >> salary;
cout << "\n Enter the roll:";
cin >> roll;
}
void putname( )
{
cout << "Employees" << salary <<
"and roll is" << roll << '\n';
}
};
void main()
{
Details det[MAX];
int n=0;
char ans;
do{
cout << "Enter the Employee Number::" << n+1;
det[n++].getname;
cout << "Enter another (y/n)?: " ;
cin >> ans;
} while ( ans != 'n' );
for (int j=0; j<n; j++)
{
cout << "\nEmployee Number is:: " << j+1;
det[j].putname( );
}
}

Result:



Enter the Employee Number:: 1
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: y
Enter the Employee Number:: 2
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: n

Array Of Objects With Classes

#include<iostream.h>
#include<conio.h>

class account
{
int accno;

public:
int balance;

void accept()
{
cout<<endl<<"Enter account no:";
cin>>accno;
cout<<"Enter balance:";
cin>>balance;

}

void display()
{
cout<<"-Balance after given interest of 10%:- "<<endl;
cout<<"Account no:"<<accno;
cout<<endl<<"Balance:"<<balance<<endl;
}
}a[10];

void main()
{
int i,balance;
clrscr();
for(i=0;i<10;i++)
{
a[i].accept();
if(a[i].balance>=5000)
{
a[i].balance=a[i].balance+(a[i].balance*0.1);
a[i].display();
}

}
getch();
}
/*Output:
Enter account no:45
Enter balance:5000
-Balance after given interest of 10%:-
Account no:45
Balance:5500

Enter account no:22
Enter balance:2000

Enter account no:48
Enter balance:200

Enter account no:33
Enter balance:100

Enter account no:66
Enter balance:777

Enter account no:88
Enter balance:100

Enter account no:19
Enter balance:9000
-Balance after given interest of 10%:-
Account no:19
Balance:9900

Enter account no:30
Enter balance:200

Enter account no:99
Enter balance:7777
-Balance after given interest of 10%:-
Account no:99
Balance:8554

Enter account no:77
Enter balance:1200

*/

Please Comment for any program down in the comment box.


Class and Objects Program

#include<iostream.h>
#include<conio.h>
class day        //class
{
int hrs,min,sec;
public:
void accept()
{
cout<<"Enter min:";
cin>>min;
}
void display()
{
if(min>60)
{
hrs=min/60;
min=min%60;
cout<<hrs<<":"<<min;
}
else
{
sec=min*60;
cout<<sec;
}
}
};
void main()
{
clrscr();
day d;     //object
d.accept();
d.display();
getch();
}
/*Output:
Enter min:138
2:18 */

Simple Example For Class

#include<iostream.h>
#include<conio.h>
class calender
{
private:
int day,month,year;
public:
void accept()
{
cout<<"Enter the day,month,year:";
cin>>day>>month>>year;
}
void display()
{
cout<<day<<"/"<<month<<"/"<<year;
}
};
void main()
{
calender c;
clrscr();
c.accept();
c.display();
getch();
}

/*OUTPUT:
Enter the day,month,year:2 4 2016
2/4/2016*/

Please Comment for any program down in the comment box.


Basic program for printing Hello World

#include<iostream.h>
#include<conio.h>

void main()
{

cout<<"Hello World";
getch();

}

What is C++

C++ is a general-purpose programming language. It has imperativeobject oriented and generic programming features, while also providing facilities for low-level memory manipulation.

C++ is an object oriented programming (OOP) language, developed by Bjarne Stroustrup, and is an extension of C language. It is therefore possible to code C++ in a "C style" or "object-oriented style." In certain scenarios, it can be coded in either way and is thus an effective example of a hybrid language.

C++ is a general purpose object oriented programming language. It is considered to be an intermediate level language, as it encapsulates both high and low level language features. Initially, the language was called 'C with classes’ as it had all properties of C language with an additional concept of 'classes’. However, it was renamed to C++ in 1983.
It is pronounced "C-Plus-Plus."
It was designed with a bias toward system programming and embedded, resource-constrained and large systems, with performance, efficiency and flexibility of use as its design highlights.[4] C++ has also been found useful in many other contexts, with key strengths being software infrastructure and resource-constrained applications,[4] including desktop applications, servers (e.g. e-commerce,web search or SQL servers), and performance-critical applications (e.g. telephone switches or space probes).[5] C++ is a compiledlanguage, with implementations of it available on many platforms and provided by various organizations, including the FSFLLVM,MicrosoftIntel and IBM.

Definition - What does C++ Programming Language mean?

C++ is an object oriented programming (OOP) language, developed by Bjarne Stroustrup, and is an extension of C language. It is therefore possible to code C++ in a "C style" or "object-oriented style." In certain scenarios, it can be coded in either way and is thus an effective example of a hybrid language.
C++ is a general purpose object oriented programming language. It is considered to be an intermediate level language, as it encapsulates both high and low level language features. Initially, the language was called 'C with classes’ as it had all properties of C language with an additional concept of 'classes’. However, it was renamed to C++ in 1983.
It is pronounced "C-Plus-Plus."
C++ is one of the most popular languages primarily utilized with system/application software, drivers, client-server applications and embedded firmware.

The main highlight of C++ is a collection of pre-defined classes, which are data types that can be instantiated multiple times. The language also facilitates declaration of user defined classes. Classes can further accommodate member functions to implement specific functionality. Multiple objects of a particular class can be defined to implement the functions within the class. Objects can be defined as instances created at run time. These classes can also be inherited by other new classes which take in the public and protected functionalities by default. 

Basics Of C++

Basics of C++

In this section we will cover the basics of C++, it will include the syntax, variable, operators, loop types, pointers, references and information about other requirements of a C++ program. You will come across lot of terms that you have already studied in C language.


First C++ program

include <iostream>
using namespace std;
int main()
{
cout << "Hello this is C++";
}
Header files are included at the beginning just like in C program. 
Here iostream.h is a header file which provides us with input & output streams. Header files contained declared function libraries, which can be used by users for their ease.
We,also use the conio.h header file used for the getch() at the end when we are using void return type with the main() function. 
Example :cout << "A";
main(), is the function which holds the executing part of program

Predefined Streams in C and C++:


C and C++ compiler has some predefined streams which indicate some standard devices. These predefined streams are automatically opened when C/C++ program is started. The <stdio.h> header file contains the definition of these predefined streams. Predefined streams used in C and C++ and its meanings are mentioned below. 

Name                                      Meaning
stdin                                                             Standard input device
stdout                                                           Standard output device
stderr                                                           Standard error output device
stdaux                                                           Standard auxiliary device
stdprn                                                           Standard printer


When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and Instance variables mean.
  • Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.
  • Class - A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.
  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

C++ Program Structure:

#include<iostream>
#include<conio.h>

// main() is where program execution begins.

void main()
{
   cout << "Hello World"; // prints Hello World
   getch();
}

C++ Keywords:

Keywords are the reserved words which C++ compiler uses for its internal purposes.

Some of the ketwords supported by C++ are:-

asmelsenewthis
autoenumoperatorthrow
boolexplicitprivatetrue
breakexportprotectedtry
caseexternpublictypedef
catchfalseregistertypeid
charfloatreinterpret_casttypename
classforreturnunion
constfriendshortunsigned
const_castgotosignedusing
continueifsizeofvirtual
defaultinlinestaticvoid
deleteintstatic_castvolatile
dolongstructwchar_t
doublemutableswitchwhile
dynamic_castnamespacetemplate


Here are a few other C++ features that are useful to know.
1.     When you define a class Stack, the name Stack becomes usable as a type name as if created with typedef and enums.

2.     You can define functions inside of a class definition, whereupon they become inline functions, which are expanded in the body of the function where they are used. The rule of thumb to follow is to only consider inlining one-line functions, and even then do so rarely.
As an example, we could make the Full routine an inline.
class Stack {
   ...
   //Variable Declarations;
   //Fuctions Declarations;
   ...
};
3.     Comments can begin with the characters // and extend to the end of the line. These are usually more handy than the /* */ style of comments.

4.     C++ provides some new opportunities to use the const keyword from ANSI C. The basic idea of const is to provide extra information to the compiler about how a variable or function is used, to allow it to flag an error if it is being used improperly. You should always look for ways to get the compiler to catch bugs for you. After all, which takes less time? Fixing a compiler-flagged error, or chasing down the same bug using gdb?
For example, you can declare that a member function only reads the member data, and never modifies the object:
class Stack
{
   ...
   accept() const;  // accept() never modifies member data
   ...
};
As in C, you can use const to declare that a variable is never modified:
    const int InitialHashTableSize = 8;

This is much better than using #define for constants, since the above is type-checked.

Input/output in C++ can be done with the >> and << operators and the objects cin and cout. For example, to write to stdout:
    cout << "Hello world no.=" << 3;

This is equivalent to the normal C code:

                 printf("Hello world no.= %d", 3);