Learn C++
http://www.cppforschool.com/
General
C++ Program Structure
General Structure:
header comments
includes
using directive
function signature {
object (or
variable) declarations
statements
}
Example:
// The header comments go at
// the beginning of your code
// to tell what its about
#include
<iostream> // included code
provides stuff which other programmers wrote
using namespace
std; // a using directive instructs the
compiler to use what was included
int main ()
{
// the signature gives the return type, func. name, and parameters
string
name;
// typically put all variable declarations after the func. signature
cout <<
"What is your name?
";
// statements are the action part of
cin
>>
name;
// your program, they direct the com-
cout <<
"Hello, " << name <<
endl;
// puter what to do; the last statement
return
0;
// should always be a return
}
Explanation
|
Like any other programming
language C++ also follows some basic structure to develop a program.
Basic Structure of C++ program:
#include directive
Global Declarations
return-type main()
{
Statements
}
Include Directive:
The "#include" directive
is used to include the files specifed inside the "<>"
brackets. Mostly standard files or header files of C++ are included using
this directive like iostream.h, math.h etc.
Global Declarations:
The variables and other elements
that need to be used all over the program or rather globally should be
declared after the include directive.
main() Function:
The main function is executed
first in a C++ program. If a main() is supposed to return a integer value
then the return type should be specified as "int main()". If no
value is returned simply use the return-type as "void".
The statements used inside the
"main()" function can include the functions, classes used in C++
along with other statements.
For Example:
#include
<iostream.h>
void main()
{
cout <<
"Hscripts.com!";
}
The above is the example of a
structure in C++.
|
STRUCTURE
OF C++ PROGRAM
#include<header file>
main ()
{
...........
...........
...........
}
main ()
{
...........
...........
...........
}
A C++ program starts with function
called main ( ). The body of the function is enclosed between curly braces. The
program statements are written within the braces. Each statement must end by a
semicolon;(statement terminator). A C++ program may contain as many functions
as required. However, when the program is loaded in the memory, the control is
handed over to function main ( ) and it is the first function to be executed.
// This is my first program is C++
/* this program will illustrate different components of
a simple program in C++ */
# include <iostream.h>
int main ( )
{
cout <<"Hello World!";
return 0;
}
/* this program will illustrate different components of
a simple program in C++ */
# include <iostream.h>
int main ( )
{
cout <<"Hello World!";
return 0;
}
When the above program is compiled,
linked and executed, the following output is displayed on the VDU screen.
Hello World!
Various components of this program
are discussed below:
Comments
First three lines of the above
program are comments and are ignored by the compiler. Comments are included in
a program to make it more readable. If a comment is short and can be
accommodated in a single line, then it is started with double slash sequence in
the first line of the program. However, if there are multiple lines in a
comment, it is enclosed between the two symbols /* and */
#include
<iostream.h>
The line in the above program that
start with # symbol are called directives and are instructions to the compiler.
The word include with '#' tells the compiler to include the file iostream.h
into the file of the above program. File iostream.h is a header file needed for
input/ output requirements of the program. Therefore, this file has been
included at the top of the program.
int
main ( )
The word main is a function name.
The brackets ( ) with main tells that main ( ) is a function. The word int
before main ( ) indicates that integer value is being returned by the function
main (). When program is loaded in the memory, the control is handed over to
function main ( ) and it is the first function to be executed.
Curly
bracket and body of the function main ( )
A C++ program starts with function called
main(). The body of the function is enclosed between curly braces. The program
statements are written within the brackets. Each statement must end by a
semicolon, without which an error message in generated.
cout<<"Hello
World!";
This statement prints our
"Hello World!" message on the screen. cout understands that anything
sent to it via the << operator should be printed on the screen.
return
0;
This is a new type of statement,
called a return statement. When a program finishes running, it sends a value to
the operating system. This particular return statement returns the value of 0
to the operating system, which means “everything went okay!”.
/* This program illustrates how to
declare variable, read data and display data. */
#include <iostream.h>
int main()
{
int rollno; //declare the variable rollno of type int
float marks; //declare the variable marks of type float
cout << "Enter roll number and marks :";
cin >> rollno >> marks; //store data into variable rollno & marks
cout << "Rollno: " << rollno<<"\n";
cout << "Marks: " << marks;
return 0;
}
declare variable, read data and display data. */
#include <iostream.h>
int main()
{
int rollno; //declare the variable rollno of type int
float marks; //declare the variable marks of type float
cout << "Enter roll number and marks :";
cin >> rollno >> marks; //store data into variable rollno & marks
cout << "Rollno: " << rollno<<"\n";
cout << "Marks: " << marks;
return 0;
}
Sample Run: In this sample run, the user input is shaded.
Enter roll number and marks :102
87.5
Rollno: 102
Marks: 87.5
Rollno: 102
Marks: 87.5
OOP CONCEPTS
Paradigm-: It means organizing principle of a program. It is an approach to programming.Procedural Paradigm
In procedural programming paradigm, the emphasis is on doing things i.e., the procedure or the algorithm. The data takes the back seat in procedural programming paradigm. Also, this paradigm does not model real world well.
Object Oriented programming
The object oriented programming paradigm models the real world well and overcomes the shortcomings of procedural paradigm. It views a problem in terms of objects and thus emphasizes on both procedures as well as data.
The following are the basic concepts used in object-oriented programming.
Object-: An object is an identifiable entity with some characteristics and behavior.
Class-: A class represents a group of objects that share common properties, behavior and relationships.
Data Abstraction-: Abstraction refers to act of representing essential features without including the background details or explanations.
Encapsulation-: The wrapping up of data and associated functions into a single unit is known as Encapsulation. Encapsulation implements data abstraction.
Modularity-: Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.
Inheritance-: It is the capability of one class of things to inherit capabilities or properties from another class.
Base and sub classes-: The class whose properties are inherited is called base class (or superclass) and the class that inherits the properties is known as derived class(or subclass).
Derived Class :- The class, which inherits from other classes is called derived class or Subclass.
Polymorphism-: It is the ability for a message or data to be processed in more than one form. Polymorphism is a property by which the same message can be sent to objects of several different classes. Polymorphism is implemented in C++ through virtual functions and overloading- function overloading and operator overloading.
Advantages of Object oriented programming.
Software complexity can be easily managed
Object-oriented systems can be easily upgraded
It is quite easy to partition the work in a project based on object
class enforce data-hiding, abstraction & encapsulation
A class groups its members into three sections : private, protected, and public. The private and protected members remain hidden from outside world. Thus through private and protected members, a class enforces data-hiding.
The outside world is given only the essential and necessary information through public members, rest of the things remain hidden, which is nothing but abstraction. Abstraction means representation of essential features without including the background details and explanation.
CLASSES & OBJECTS
The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called object or instance. In other words, a class would be the data type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format:class class_name
{
private:
members1;
protected:
members2;
public:
members3;
};
Where class_name is a valid identifier for the class. The body of the declaration can contain members, that can be either data or function declarations, The members of a class are classified into three categories: private, public, and protected. Private, protected, and public are reserved words and are called member access specifiers. These specifiers modify the access rights that the members following them acquire.
private members of a class are accessible only from within other members of the same class. You cannot access it outside of the class.
protected members are accessible from members of their same class and also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access.
Here is a complete example :
class
student
{
private :
int rollno;
float marks;
public:
void getdata()
{
cout<<"Enter Roll Number
: ";
cin>>rollno;
cout<<"Enter Marks :
";
cin>>marks;
}
void displaydata()
{
cout<<"Roll number :
"<<rollno<<"\nMarks : "<<marks;
}
};
Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for declaring a object is the same as that for declaring any other variable. The following statements declare two objects of type student: student st1, st2;
Accessing Class Members
Once an object of a class is declared, it can access the public members of the class. st1.getdata();
Defining Member function of class
You can define Functions inside the class as shown in above example. Member functions defined inside a class this way are created as inline functions by default. It is also possible to declare a function within a class but define it elsewhere. Functions defined outside the class are not normally inline.When we define a function outside the class we cannot reference them (directly) outside
of the class. In order to reference these, we use the scope resolution operator, ::
(double colon). In this example, we are defining function getdata outside the class:
void student :: getdata()
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
The following program demostrates the general feature of classes. Member function initdata() is defined inside the class. Member funcitons getdata() and showdata() defined outside the class.
class student //specify a class
{
private :
int rollno; //class data members
float marks;
public:
void initdata(int r, int m)
{
rollno=r;
marks=m;
}
void getdata(); //member function to get data from
user
void showdata();// member function to show data
};
void student :: getdata()
{
cout<<"Enter Roll Number : ";
cin>>rollno;
cout<<"Enter Marks : ";
cin>>marks;
}
void student :: showdata()
{
cout<<"Roll number :
"<<rollno<<"\nMarks : "<<marks;
}
int main()
{
student st1, st2; //define two objects of class
student
st1.initdata(5,78); //call member function to
initialize
st1.showdata();
st2.getdata(); //call member function to input data
st2.showdata(); //call member function to display data
return 0;
}
CONSTRUCTOR AND DESTRUCTOR
CONSTURCTOR
It is a member function having same name as it’s class and which is used to initialize the objects of that class type with a legel initial value. Constructor is automatically called when object is created.Types of Constructor
Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor.student :: student()
{
rollno=0;
marks=0.0;
}
Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor.
student :: student(int r)
{
rollno=r;
}
Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object.
student :: student(student &t)
{
rollno = t.rollno;
}
There can be multiple constructors of the same class, provided they have different signatures.
DESTRUCTOR
A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object’s scope is over.~student() { }
Example : In the following program constructors, destructor and other member functions are defined inside class definitions. Since we are using multiple constructor in class so this example also illustrates the concept of constructor overloading
#include<iostream.h>
class student //specify a class
{
private :
int rollno; //class data members
float marks;
public:
student() //default constructor
{
rollno=0;
marks=0.0;
}
student(int r, int m) //parameterized constructor
{
rollno=r;
marks=m;
}
student(student &t) //copy constructor
{
rollno=t.rollno;
marks=t.marks;
}
void getdata() //member function to get data from user
{
cout<<"Enter Roll Number :
";
cin>>rollno;
cout<<"Enter Marks :
";
cin>>marks;
}
void showdata() // member function to show data
{
cout<<"\nRoll number:
"<<rollno<<"\nMarks: "<<marks;
}
~student() //destructor
{}
};
int main()
{
student st1; //defalut constructor invoked
student st2(5,78); //parmeterized constructor invoked
student st3(st2); //copy constructor invoked
st1.showdata(); //display data members of object st1
st2.showdata(); //display data members of object st2
st3.showdata(); //display data members of object st3
return 0;
}
INHERITANCE
Inheritance:It is the capability of one class to inherit properties from another class.Base Class: It is the class whose properties are inherited by another class. It is also called Super Class.
Derived Class:It is the class that inherit properties from base class(es).It is also called Sub Class.
FORMS OF INHERITANCE
Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class.Multiple Inheritance:It is the inheritance hierarchy wherein one derived class inherits from multiple base class(es)
Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherits from one base class.
Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
Hybrid Inheritance:The inheritance hierarchy that reflects any legal combination of other four types of inheritance.
Visibility Mode:It is the keyword that controls the visibility and availability of inherited base class members in the derived class.It can be either private or protected or public.
Private Inheritance:It is the inheritance facilitated by private visibility mode.In private inheritance ,the protected and public members of base class become private members of the derived class.
Public Inheritance:It is the inheritance facilitated by public visibility mode.In public inheritance ,the protected members of base class become protected members of the derived class and public members of the base class become public members of derived class.;
Protected Inheritance:It is the inheritance facilitated by protected visibility mode.In protected inheritance ,the protected and public members of base class become protected members of the derived class.
Base Class Visibility
|
Derived class visibility
|
||
Public derivation
|
Private derivation
|
Protected derivation
|
|
Private
|
Not inherited
|
Not inherited
|
Not inherited
|
Protected
|
Protected
|
Private
|
Protected
|
Public
|
Public
|
Private
|
Protected
|
Execution of base class constructor
Method of inheritace
|
Order of execution
|
class B : public A { };
|
A(); base constructor
B(); derived constructor |
class A : public B, public C
|
B();base (first)
C();base (second) A();derived constructor |
Overriding of method(function) in inheritance
We may face a problem in multiple inheritance, when a function with the same name appears in more than one base class. Compiler shows ambiguous error when derived class inherited by these classes uses this function.We can solve this problem, by defining a named instance within the derived class, using the class resolution operator with the function as below :
class P : public M, public N //multiple inheritance
{
public :
void display() //overrides display() of M and N
{
M::display()
}
};
we can now used the derived class as follows :
void main()
{
P obj;
obj.display();
}
Virtual Base Class
Multipath inheritance may lead to duplication of inherited members from a grandparent base class. This may be avoided by making the common base class a virtual base class. When a class is made a virtual base class, C++ takes necessary care to see that only one copy of that class is inherited.class A
{
....
....
};
class B1 : virtual public A
{ ....
....
};
class B2 : virtual public A
{
....
....
};
class C : public B1, public B2
{
.... // only one copy of A
.... // will be inherited
};
DATA FILE HANDLING IN C++
File. The information / data stored under a specific name on a storage device, is called a file.Stream. It refers to a sequence of bytes.
Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here.
Classes for file stream operation
ofstream: Stream class to write on filesifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTORofstream fout(“results”); //output only
ifstream fin(“data”); //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode)
ofstream ofile;
ofile.open(“data1”);
ifstream ifile;
ifile.open(“data2”);
File mode parameter
|
Meaning
|
ios::app
|
Append to end of file
|
ios::ate
|
go to end of file on opening
|
ios::binary
|
file open in binary mode
|
ios::in
|
open file for reading only
|
ios::out
|
open file for writing only
|
ios::nocreate
|
open fails if the file does not exist
|
ios::noreplace
|
open fails if the file already exist
|
ios::trunc
|
delete the contents of the file if it exist
|
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
CLOSING FILE
fout.close();fin.close();
INPUT AND OUTPUT OPERATION
put() and get() functionthe function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTION
|
RETURN VALUE AND MEANING
|
eof()
|
returns true (non zero) if end of file is encountered
while reading; otherwise return false(zero)
|
fail()
|
return true when an input or output operation has failed
|
bad()
|
returns true if an invalid operation is attempted or any
unrecoverable error has occurred.
|
good()
|
returns true if no error has occurred.
|
FILE POINTERS AND THEIR MANIPULATION
All i/o streams objects have, at least, one internal stream pointer:ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream).
These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:
seekg()
|
moves get pointer(input) to a specified location
|
seekp()
|
moves put pointer (output) to a specified location
|
tellg()
|
gives the current position of the get pointer
|
tellp()
|
gives the current position of the put pointer
|
The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example:
file.seekg(-10, ios::cur);
BASIC OPERATION ON TEXT FILE IN C++
Program to write in a text file
#include<fstream.h>int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]="Time is a great teacher but unfortunately it kills all its pupils. Berlioz";
fout<<str;
fout.close();
return 0;
}
Program to read from text file and display it
#include<fstream.h>#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
Program to count number of characters.
#include<fstream.h>#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
clrscr();
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of words
#include<fstream.h>#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char word[30]; int count=0;
while(!fin.eof())
{
fin>>word;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of lines
#include<fstream.h>#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char str[80]; int count=0;
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}
Program to copy contents of file to another file.
#include<fstream.h>int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
return 0;
}
BASIC OPERATION ON BINARY FILE IN C++
class student{
int admno;
char name[20];
public:
void getdata()
{
cout<<"\nEnter The admission no. ";
cin>>admno;
cout<<"\n\nEnter The Name of The Student ";
gets(name);
}
void showdata()
{
cout<<"\nAdmission no. : "<<admno;
cout<<"\nStudent Name : ";
puts(name);
}
int retadmno()
{
return admno;
}
};
function to write in a binary file
void write_data(){
student obj;
ofstream fp2;
fp2.open("student.dat",ios::binary|ios::app);
obj.getdata();
fp2.write((char*)&obj,sizeof(obj));
fp2.close();
}
function to display records of file
void display(){
student obj;
ifstream fp1;
fp1.open("student.dat",ios::binary);
while(fp1.read((char*)&obj,sizeof(obj)))
{
obj.showdata();
}
}
fp.close();
}
Function to search and display from binary file
void search (int n){
student obj;
ifstream fp1;
fp1.open("student.dat",ios::binary);
while(fp1.read((char*)&obj,sizeof(obj)))
{
if(obj.retadmno()==n)
obj.showdata();
}
fp1.close();
}
Function to delete a record
void deleterecord(int n){
student obj;
ifstream fp1;
fp1.open("student.dat",ios::binary);
ofstream fp2;
fp2.open("Temp.dat",ios::out|ios::binary);
while(fp1.read((char*)&obj,sizeof(obj)))
{
if(obj.retadmno!=n)
fp2.write((char*)&obj,sizeof(obj));
}
fp1.close();
fp2.close();
remove("student.dat");
rename("Temp.dat","student.dat");
}
Function to modify a record
void modifyrecord(int n){
fstream fp;
student obj;
int found=0;
fp.open("student.dat",ios::in|ios::out);
while(fp.read((char*)&obj,sizeof(obj)) && found==0)
{
if(obj.retadmno()==n)
{
obj.showdata();
cout<<"\nEnter The New Details of student";
obj.getdata();
int pos=-1*sizeof(obj);
fp.seekp(pos,ios::cur);
fp.write((char*)&obj,sizeof(obj));
found=1;
}
}
fp.close();
}
C++ Programming Tutorial
http://www.programiz.com/cpp-programming
C++ programming is on the one the most popular and widely used object-oriented programming language which was developed by Bjarne Stroustrup in 1979. C++ is derived from C programming. So, almost all code that run on C runs correctly on C++. If you have good understanding of basic features of C programming, you will have a head start learning C++.Topics Covered in This C++ Programming Tutorial
C++ tutorial
|
C++ Class
A class is the collection of related data and function under a single name. A C++ program can have any number of classes. When related data and functions are kept under a class, it helps to visualize the complex problem efficiently and effectively.When a class is defined, no memory is allocated. You can imagine like a datatype.
int var;
The above code specifies var is a variable of type integer; int
is used for specifying variable var is of integer type. Similarly,
class are also just the specification for objects and object bears the property
of that class.Defining the Class in C++
Class is defined in C++ programming using keyword class followed by identifier(name of class). Body of class is defined inside curly brackets an terminated by semicolon at the end in similar way as structure.class class_name
{
// some data
// some functions
};
Example of Class in C++
class temp
{
private:
int data1;
float data2;
public:
void func1()
{ data1=2; }
float func2(){
data2=3.5;
retrun data;
}
};
ExplanationAs mentioned, definition of class starts with keyword class followed by name of class(temp) in this case. The body of that class is inside the curly brackets and terminated by semicolon at the end. There are two keywords: private and public mentioned inside the body of class.
Keywords: private and public
Keyword private makes data and functions private and keyword public makes data and functions public. Private data and functions are accessible inside that class only whereas, public data and functions are accessible both inside and outside the class. This feature in OOP is known as data hiding. If programmer mistakenly tries to access private data outside the class, compiler shows error which prevents the misuse of data. Generally, data are private and functions are public.C++ Objects
When class is defined, only specification for the object is defined. Object has same relationship to class as variable has with the data type. Objects can be defined in similary way as structure is defined.Syntax to Define Object in C++
class_name variable name;
For the above defined class temp, objects for that class can be
defined as:temp obj1,obj2;
Here, two objects(obj1 and obj2) of temp
class are defined.Data member and Member functions
The data within the class is known as data member. The function defined within the class is known as member function. These two technical terms are frequently used in explaining OOP. In the above class temp, data1 and data2 are data members and func1() and func2() are member functions.Accessing Data Members and Member functions
Data members and member functions can be accessed in similar way the member of structure is accessed using member operator(.). For the class and object defined above, func1() for object obj2 can be called using code:obj2.func1();
Similary, the data member can be accessed as:object_name.data_memeber;
Note: You cannot access the data member of the above class temp
because both data members are private so it cannot be accessed outside that
class.Example to Explain Working of Object and Class in C++ Programming
/* Program to illustrate working of Objects and Class in C++ Programming */
#include <iostream>
using namespace std;
class temp
{
private:
int data1;
float data2;
public:
void int_data(int d){
data1=d;
cout<<"Number: "<<data1;
}
float float_data(){
cout<<"\nEnter data: ";
cin>>data2;
return data2;
}
};
int main(){
temp obj1, obj2;
obj1.int_data(12);
cout<<"You entered "<<obj2.float_data();
return 0;
}
Output: Number: 12
Enter data: 12.43
You entered: 12.43
Explanation of ProgramIn this program, two data members data1 and data2 and two member function
int_data()
and float_data()
are defined
under temp class. Two objects obj1 and obj2 of
that class are declared. Function int_data()
for the obj1 is executed using code obj1.int_data(12);
,
which sets 12 to the data1 of object obj1. Then, function
float_data()
for the object obj2
is executed which takes data from user; stores it in data2 of obj2
and returns it to the calling function.Note: In this program, data2 for object obj1 and data1 for object obj2 is not used and contains garbage value.
A large program may contain many member functions. For the clarity of the code, member functions can be defined outside the class. To do so, member function should be declared inside the class(function prototype should be inside the class). Then, the function definition can be defined using scope resolution operator ::. Learn more about defining member function outside the class.
Constructors in C++ Programming
C++ Constructor
Constructors are the special type of member function that initializes the object automatically when it is created Compiler identifies that the given member function is a constructor by its name and return type. Constructor has same name as that of class and it does not have any return type...... ... .....
class temporary
{
private:
int x;
float y;
public:
temporary(): x(5), y(5.5) /* Constructor */
{
/* Body of constructor */
}
.... ... ....
}
int main()
{
Temporary t1;
.... ... ....
}
Working of ConstructorIn the above pseudo code,
temporary()
is a constructor. When the object of class temporary
is created, constructor is called and x is initialized to 5 and y
is initialized to 5.5 automatically.You can also initialize data member inside the constructor's function body as below. But, this method is not preferred.
temporary(){
x=5;
y=5.5;
}
/* This method is not preferred. /*
Use of Constructor in C++
Suppose you are working on 100's of objects and the default value of a data member is 0. Initializing all objects manually will be very tedious. Instead, you can define a constructor which initializes that data member to 0. Then all you have to do is define object and constructor will initialize object automatically. These types of situation arises frequently while handling array of objects. Also, if you want to execute some codes immediately after object is created, you can place that code inside the body of constructor.Constructor Example
/*Source Code to demonstrate the working of constructor in C++ Programming */
/* This program calculates the area of a rectangle and displays it. */
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
Area(): length(5), breadth(2){ } /* Constructor */
void GetLength()
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp;
}
};
int main()
{
Area A1,A2;
int temp;
A1.GetLength();
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<endl<<"Default Area when value is not taken from user"<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
ExplanationIn this program, a class of name Area is created to calculate the area of a rectangle. There are two data members length and breadth. A constructor is defined which initializes length to 5 and breadth to 2. And, we have three additional member functions
GetLength(), AreaCalculation() and DisplayArea()
to get length from user, calculate the area and display the area respectively.When, objects A1 and
A2
are created then, the length and breadth of both objects are initialized to 5
and 2 respectively because of the constructor. Then the member function GetLength()
is invoked which takes the
value of length and breadth from user for object A1.
Then, the area for the object A1 is calculated and stored in variable
temp by calling AreaCalculation()
function. And finally, the area of object A1 is displayed. For
object A2, no data is asked from the user. So, the value of length
will be 5 and breadth will be 2. Then, the area for A2 is
calculated and displayed which is 10.Output
Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10
Constructor Overloading
Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name(name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructor are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors./* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
Area(): length(5), breadth(2){ } // Constructor without no argument
Area(int l, int b): length(l), breadth(b){ } // Constructor with two argument
void GetLength()
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
int AreaCalculation() { return (length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp<<endl;
}
};
int main()
{
Area A1,A2(2,1);
int temp;
cout<<"Default Area when no argument is passed."<<endl;
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<"Area when (2,1) is passed as arguement."<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
Explanation of Overloaded ConstructorsFor object A1, no argument is passed. Thus, the constructor with no argument is invoked which initializes length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initializes length to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as arguement.
Area: 2
Default Copy Constructor
A object can be initialized with another object of same type. Let us suppose the above program. If you want to initialize a object A3 so that it contains same value as A2. Then, this can be performed as:....
int main() {
Area A1,A2(2,1);
Area A3(A2); /* Copies the content of A2 to A3 */
OR,
Area A3=A2; /* Copies the content of A2 to A3 */
}
You might think, you may need some constructor to perform this task. But, no
additional constructor is needed. It is because this constructor is already
built into all classes.Passing Objects and Returning Object from Function in C++ Programming
In C++ programming, objects can be passed to function in similar way as variables and structures.Procedure to Pass Object to Function
Example to Pass Object to Function
C++ program to add two complex numbers by passing objects to function.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void Read()
{
cout<<"Enter real and imaginary number respectively:"<<endl;
cin>>real>>imag;
}
void Add(Complex comp1,Complex comp2)
{
real=comp1.real+comp2.real;
/* Here, real represents the real data of object c3 because this function is called using code c3.add(c1,c2); */
imag=comp1.imag+comp2.imag;
/* Here, imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); */
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3.Add(c1,c2);
c3.Display();
return 0;
}
Output
Enter real and imaginary number respectively:
12
3
Enter real and imaginary number respectively:
2
6
Sum=14+9i
Returning Object from Function
The syntax and procedure to return object is similar to that of returning structure from function.Example to Return Object from Function
This program is the modification of above program displays exactly same output as above. But, in this program, object is return from function to perform this task.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void Read()
{
cout<<"Enter real and imaginary number respectively:"<<endl;
cin>>real>>imag;
}
Complex Add(Complex comp2)
{
Complex temp;
temp.real=real+comp2.real;
/* Here, real represents the real data of object c1 because this function is called using code c1.Add(c2) */
temp.imag=imag+comp2.imag;
/* Here, imag represents the imag data of object c1 because this function is called using code c1.Add(c2) */
return temp;
}
void Display()
{
cout<<"Sum="<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1,c2,c3;
c1.Read();
c2.Read();
c3=c1.Add(c2);
c3.Display();
return 0;
}
C++ Programming Operator Overloading
The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++ language. For example: If you want to add two integers then, + operator is used. But, for user-defined types(like: objects), you can define the meaning of operator, i.e, you can redefine the way that operator works. For example: If there are two objects of a class that contain string as its data member, you can use + operator to concatenate two strings. Suppose, instead of strings if that class contains integer data member, then you can use + operator to add integers. This feature in C++ programming that allows programmer to redefine the meaning of operator when they operate on class objects is known as operator overloading.Why Operator overloading is used in C++ programming?
You can write any C++ program without the knowledge of operator overloading. But, operator operating are profoundly used by programmer to make a program clearer. For example: you can replace the code like: calculation = add(mult(a,b),div(a,b)); with calculation = a*b+a/b; which is more readable and easy to understand.How to overload operators in C++ programming?
To overload a operator, a operator function is defined inside a class as:This operator function is called when, the operator(sign) operates on the object of that class class_name.
Example of operator overloading in C++ Programming
/* Simple example to demonstrate the working of operator overloading*/
#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
temp():count(5){ }
void operator ++() {
count=count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
temp t;
++t; /* operator function void operator ++() is called */
t.Display();
return 0;
}
Output
Count: 6
ExplanationIn this program, a operator function void operator ++ () is defined(inside class temp), which is invoked when ++ operator operates on the object of type temp. This function will increase the value of count by 1.
Things to remember while using Operator overloading in C++ language
- Operator overloading cannot be used to change the way operator works on built-in types. Operator overloading only allows to redefine the meaning of operator for user-defined types.
- There are two operators assignment operator(=) and address operator(&) which does not need to be overloaded. Because these two operators are already overloaded in C++ library. For example: If obj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without overloading = operator. This code will copy the contents object of obj2 to obj1. Similarly, you can use address operator directly without overloading which will return the address of object in memory.
- Operator overloading cannot change the precedence of operators and associativity of operators. But, if you want to change the order of evaluation, parenthesis should be used.
- Not all operators in C++ language can be overloaded. The operators that cannot be overloaded in C++ are ::(scope resolution), .(member selection), .*(member selection through pointer to function) and ?:(ternary operator).
Following best practice while using operator overloading
Operator overloading allows programmer to define operator the way they want but, there is a pitfall if operator overloading is not used properly. In above example, you have seen ++ operator operates on object to increase the value of count by 1. But, the value is increased by 1 because, we have used the code:void operator ++() {
count=count+1;
}
If the code below was used instead, then the value of count will be
decreased by 100 if ++ operates on object.void operator ++() {
count=count-100;
}
But, it does not make any sense to decrease count by 100 when ++ operator is
used. Instead of making code readable this makes code obscure and confusing.
And, it is the job of the programmer to use operator overloading properly and
in consistent manner.Again, the above example is increase count by 1 is not complete. This program is incomplete in sense that, you cannot use code like:
t1=++t
It is because the return type of operator function is void. It is generally
better to make operator work in similar way it works with basic types if
possible.Here, are the examples of operator overloading on different types of operators in C++ language in best possible ways:
- - Increment and Decrement Operator Overloading
- - Overloading of binary operator - to subtract complex number
Inheritance in C++ Programming
Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class). The derived class inherits all feature from a base class and it can have additional features of its own.Concept of Inheritance in OOP
Suppose, you want to calculate either area, perimeter or diagonal length of a rectangle by taking data(length and breadth) from user. You can create three different objects( Area, Perimeter and Diagonal) and asks user to enter length and breadth in each object and calculate corresponding data. But, the better approach would be to create a additional object Rectangle to store value of length and breadth from user and derive objects Area, Perimeter and Diagonal from Rectangle base class. It is because, all three objects Area, Perimeter and diagonal are related to object Rectangle and you don't need to ask user the input data from these three derived objects as this feature is included in base class.Implementation of Inheritance in C++ Programming
class Rectangle
{
... .. ...
};
class Area : public Rectangle
{
... .. ...
};
class Perimeter : public Rectangle
{
.... .. ...
};
In the above example, class Rectangle is a base class and classes
Area and Perimeter are the derived from Rectangle.
The derived class appears with the declaration of class followed by a colon,
the keyword public and the name of base class from which it is
derived.Since, Area and Perimeter are derived from Rectangle, all data member and member function of base class Rectangle can be accessible from derived class.
Note: Keywords private and protected can be used in place
of public while defining derived class(will be discussed later).
Source Code to Implement Inheritance in C++ Programming
This example calculates the area and perimeter a rectangle using the concept of inheritance.
/* C++ Program to calculate the area and perimeter of rectangles using concept of inheritance. */
#include <iostream>
using namespace std;
class Rectangle
{
protected:
float length, breadth;
public:
Rectangle(): length(0.0), breadth(0.0)
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}
};
/* Area class is derived from base class Rectangle. */
class Area : public Rectangle
{
public:
float calc()
{
return length*breadth;
}
};
/* Perimeter class is derived from base class Rectangle. */
class Perimeter : public Rectangle
{
public:
float calc()
{
return 2*(length+breadth);
}
};
int main()
{
cout<<"Enter data for first rectangle to find area.\n";
Area a;
cout<<"Area = "<<a.calc()<<" square meter\n\n";
cout<<"Enter data for second rectangle to find perimeter.\n";
Perimeter p;
cout<<"\nPerimeter = "<<p.calc()<<" meter";
return 0;
}
OutputEnter data for first rectangle to find area.
Enter length: 5
Enter breadth: 4
Area = 20 square meter
Enter data for second rectangle to find perimeter.
Enter length: 3
Enter breadth: 2
Area = 10 meter
Explanation of ProgramIn this program, classes Area and Perimeter are derived from class Rectangle. Thus, the object of derived class can access the public members of Rectangle. In this program, when objects of class Area and Perimeter are created, constructor in base class is automatically called. If there was public member function in base class then, those functions also would have been accessible for objects a and p.
Keyword protected
In this program, length and breadth in the base class are protected data members. These data members are accessible from the derived class but, not accessible from outside it. This maintains the feature of data hiding in C++ programming. If you defined length and breadth as private members then, those two data are not accessible to derived class and if defined as public members, it can be accessible from both derived class and frommain( )
function.
Accessbility
|
private
|
protected
|
public
|
Accessible from own class ?
|
yes
|
yes
|
yes
|
Accessible from dervied class ?
|
no
|
yes
|
yes
|
Accessible outside dervied class ?
|
no
|
no
|
yes
|
Member Function Overriding in Inheritance
Suppose, base class and derived class have member functions with same name and arguments. If you create an object of derived class and write code to access that member function then, the member function in derived class is only invoked, i.e., the member function of derived class overrides the member function of base class.Public, Protected and Private Inheritance in C++ Programming
You can declare a derived class from a base class with different access control, i.e., public inheritance, protected inheritance or private inheritance.class base
{
.... ... ....
};
class derived : access_specifier base
{
.... ... ....
};
/* Note: Either keyword public, protected or private is used in place of access_specifier. */
Things to remember while Using Public, Protected and Private Inheritance
- Protected and public members(data and function) of a base class are accessible from a derived class(for all three: public, protected and private inheritance).
- Objects of derived class with private and protected inheritance cannot access any data member of a base class.
- Objects of derived class with public inheritance can access only public member of a base class.
Summary of Public, Protected and Private Inheritance
Accessibility in Public Inheritance
Accessibility
|
private
|
protected
|
public
|
Accessible from own class?
|
yes
|
yes
|
yes
|
Accessible from dervied class?
|
no
|
yes
|
yes
|
Accessible outside dervied class?
|
no
|
no
|
yes
|
Accessibility in Protected Inheritance
Accessibility
|
private
|
protected
|
public
|
Accessible from own class?
|
yes
|
yes
|
yes
|
Accessible from dervied class?
|
no
|
yes
|
yes
|
Accessible outside dervied class?
|
no
|
no
|
no
|
Accessibility in Private Inheritance
Accessibility
|
private
|
protected
|
public
|
Accessible from own class?
|
yes
|
yes
|
yes
|
Accessible from dervied class?
|
no
|
yes
|
yes
|
Accessible outside dervied class?
|
no
|
no
|
no
|
Multilevel Inheritance and Multiple Inheritance in C++ Programming
Levels of Inheritance
In C++ programming, a class be can derived from a derived class which is known as multilevel inhertiance. For example:class A
{ .... ... .... };
class B : public A
{ .... ... .... };
class C : public B
{ .... ... .... };
In this example, class B is derived from class A and
class C is derived from derived class B.Example to Demonstrate the Multilevel Inheritance
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
OutputBase class content.
Explanation of ProgramIn this program, class B is derived from A and C is derived from B. An object of class C is defined in
main( )
function. When the display( )
function is called, display( )
in class A is
executed because there is no display( )
function in C and B. The program first looks for display( )
in class C first but, can't
find it. Then, looks in B because C is derived from B.
Again it can't find it. And finally looks it in A and executes the
codes inside that function.If there was
display( )
function in C too, then it would have override display( )
in A because of member function overriding.Multiple Inheritance in C++
In C++ programming, a class can be derived from more than one parents. For example: A class Rectangle is derived from base classes Area and Circle.Source Code to Implement Multiple Inheritance in C++ Programming
This program calculates the area and perimeter of an rectangle but, to perform this program, multiple inheritance is used.
#include <iostream>
using namespace std;
class Area
{
public:
float area_calc(float l,float b)
{
return l*b;
}
};
class Perimeter
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};
/* Rectangle class is derived from classes Area and Perimeter. */
class Rectangle : private Area, private Perimeter
{
private:
float length, breadth;
public:
Rectangle() : length(0.0), breadth(0.0) { }
void get_data( )
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}
float area_calc()
{
/* Calls area_calc() of class Area and returns it. */
return Area::area_calc(length,breadth);
}
float peri_calc()
{
/* Calls peri_calc() function of class Perimeter and returns it. */
return Perimeter::peri_calc(length,breadth);
}
};
int main()
{
Rectangle r;
r.get_data();
cout<<"Area = "<<r.area_calc();
cout<<"\nPerimeter = "<<r.peri_calc();
return 0;
}
OutputEnter length: 5.1
Enter breadth: 2.3
Area = 11.73
Perimeter = 14.8
Note: This program is intended to give you idea on how
multiple inheritance works rather than the condition in which multiple
inheritance is used.
Ambiguity in Multiple Inheritance
Multiple inheritance may be helpful in certain cases but, sometimes odd sort of problem encounters while using multiple inheritance. For example: Two base classes have functions with same name which is not overridden in derived class and if you write code to access that function using object of derived class, compiler shows error because, it cannot determine which function to call. Here is a code for this type of ambiguity in multiple inheritance
class base1
{
public:
void some_function( )
{ .... ... .... }
};
class base2
{
void some_function( )
{ .... ... .... }
};
class derived : public base1, public base2
{
};
int main()
{
derived obj;
/* Error because compiler can't figure out which function to call either same_function( ) of base1 or base2 .*/
obj.same_function( )
}
But, this problem can be solved easily using scope resolution function to
specify which function to class either base1 or base2int main()
{
obj.base1::same_function( ); /* Function of class base1 is called. */
obj.base2::same_function( ); /* Function of class base2 is called. */
}
Function Overriding in C++ Programming
If base class and derived class have member functions with same name and arguments. If you create an object of derived class and write code to access that member function then, the member function in derived class is only invoked, i.e., the member function of derived class overrides the member function of base class. This feature in C++ programming is known as function overriding.Accessing the Overridden Function in Base Class From Derived Class
To access the overridden function of base class from derived class, scope resolution operator ::. For example: If you want to accessget_data()
function of base class from
derived class in above example then, the following statement is used in derived
class.A::get_data; // Calling get_data() of class A.
It is because, if the name of class is not specified, the compiler thinks get_data()
function is calling itself.Virtual Function in C++ Programming
If there are member function with same name in derived classes, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. This feature in C++ programming is known as polymorphism which is one of the important feature of OOP.If a base class and derived class has same function and if you write code to access that function using pointer of base class then, the function in the base class is executed even if, the object of derived class is referenced with that pointer variable. This can be demonstrated by an example.
#include <iostream>
using namespace std;
class B
{
public:
void display()
{ cout<<"Content of base class.\n"; }
};
class D : public B
{
public:
void display()
{ cout<<"Content of derived class.\n"; }
};
int main()
{
B *b;
D d;
b->display();
b = &d; /* Address of object d in pointer variable */
b->display();
return 0;
}
Note: An object(either normal or pointer) of derived class
is type compatible with pointer to base class. So,
Outputb = &d;
is allowed in above program.Content of base class.
Content of base class.
In above program, even if the object of derived class d is put in
pointer to base class, display( )
of the base class is executed( member function of the class that matches the
type of pointer ).Virtual Functions
If you want to execute the member function of derived class then, you can declaredisplay( )
in the
base class virtual which makes that function existing in appearance only but,
you can't call that function. In order to make a function virtual, you have to
add keyword virtual in front of a function./* Example to demonstrate the working of virtual function in C++ programming. */
#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};
class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};
int main()
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here because the function of base class is virtual. */
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}
OutputContent of first derived class.
Content of second derived class.
After the function of base class is made virtual, code b->display( )
will call the display( )
of the derived class
depending upon the content of pointer.In this program,
display( )
function of two different classes are called with same code which is one of the
example of polymorphism in C++ programming using virtual functions.C++ Abstract class and Pure virtual Function
In C++ programming, sometimes inheritance is used only for the better visualization of data and you do not need to create any object of base class. For example: If you want to calculate area of different objects like: circle and square then, you can inherit these classes from a shape because it helps to visualize the problem but, you do not need to create any object of shape. In such case, you can declare shape as a abstract class. If you try to create object of a abstract class, compiler shows error.Declaration of a Abstract Class
If expression=0
is added to a virtual function then, that function is becomes pure virtual
function. Note that, adding =0
to virtual function does not assign value, it simply indicates the virtual
function is a pure function. If a base class contains at least one virtual
function then, that class is known as abstract class.Example to Demonstrate the Use of Abstract class
#include <iostream>
using namespace std;
class Shape /* Abstract class */
{
protected:
float l;
public:
void get_data() /* Note: this function is not virtual. */
{
cin>>l;
}
virtual float area() = 0; /* Pure virtual function */
};
class Square : public Shape
{
public:
float area()
{ return l*l; }
};
class Circle : public Shape
{
public:
float area()
{ return 3.14*l*l; }
};
int main()
{
Square s;
Circle c;
cout<<"Enter length to calculate area of a square: ";
s.get_data();
cout<<"Area of square: "<<s.area();
cout<<"\nEnter radius to calcuate area of a circle:";
c.get_data();
cout<<"Area of circle: "<<c.area();
return 0;
}
In this program, pure virtual function virtual
float area() = 0;
is defined inside class Shape, so
this class is an abstract class and you cannot create object of class ShapeC++ Programming friend Function and friend Classes
One of the important concept of OOP is data hiding, i.e., a nonmember function cannot access an object's private or protected data. But, sometimes this restriction may force programmer to write long and complex codes. So, there is mechanism built in C++ programming to access private or protected data from non-member function which is friend function and friend class.friend Function in C++
If a function is defined as a friend function then, the private and protected data of class can be accessed from that function. The complier knows a given function is a friend function by its keyword friend. The declaration of friend function should be made inside the body of class (can be anywhere inside class either in private or public section) starting with keyword friend.class class_name
{
...... .... ........
friend return_type function_name(argument/s);
...... .... ........
}
Now, you can define friend function of that name and that function can
access the private and protected data of that function. No keywords in used in
function definition of friend function.Example to Demonstrate working of friend Function
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d) //function definition
{
d.meter=5; //accessing private data from non-member function
return d.meter;
}
int main()
{
Distance D;
cout<<"Distace: "<<func(D);
return 0;
}
OutputDistance: 5
Here, friend function func()
is declared inside Distance class. So, the private data can be accessed from
this function.Though this example gives you what idea about the concept of friend function, this program doesn't give you idea about when friend function is helpful.
Suppose, you need to operate on objects of two different class then,friend function can be very helpful. You can operate on two objects of different class without using friend function but, you program will be long, complex and hard to understand.
Example to operate on Objects of two Different class using friend Function
#include <iostream>
using namespace std;
class B; // forward declaration
class A {
private:
int data;
public:
A(): data(12){ }
friend int func(A , B); //friend function Declaration
};
class B {
private:
int data;
public:
B(): data(1){ }
friend int func(A , B); //friend function Declaration
};
int func(A d1,B d2)
/*Function func() is the friend function of both classes A and B. So, the private data of both class can be accessed from this function.*/
{
return (d1.data+d2.data);
}
int main()
{
A a;
B b;
cout<<"Data: "<<func(a,b);
return 0;
}
In this program, classes A and B has declared func()
as a friend function. Thus, this function can
access private data of both class. In this program, two objects of two
different class A and B are passed as an argument to friend function. Thus,
this function can access private and protected data of both class. Here, func()
function adds private data of two
objects and returns it to main function.To work this program properly, a forward declaration of a class should be made as in above example(forward declaration of class B is made). It is because class B is referenced from class A using code: friend int func(A , B);. So, class A should be declared before class B to work properly.
friend Class in C++ Programming
Similarly like, friend function. A class can be made a friend of another class using keyword friend. For example:........ ..... ........
class A{
friend class B; // class B is a friend class
..... ..... .....
}
class B{
..... ..... .....
}
When a class is made a friend class, all the member functions of that class
becomes friend function. In this program, all member functions of class B will
be friend function of class A. Thus, any member function of class B can access
the private and protected data of class A.If B is declared friend class of A then, all member functions of class B can access private data and protected data of class A but, member functions of class A cannot private and protected data of class B. Remember, friendship relation in C++ is granted not taken.
Templates in C++ Programming
Templates in C++ programming allows function or class to work on different data types without writing different codes for different data types. Templates are often used in larger software and program for the purpose of code reusability and flexibility of program.Function Templates
A function templates works in similar manner as function except a single function template can work on different types but, different functions are needed to perform identical task on different data. If you need to perform identical operations on two or more types of data then, you can use function overloading. But, the better approach would be to use function templates because you can perform this task by writing less code and code is easier to maintain.How to define function template?
A function template starts with keyword template followed by template parameter/s inside < > which is followed by function declaration.template <class T>
T some_function(T arg)
{
.... ... ....
}
In above code, T is a template argument and class is a
keyword. You can use keyword typename
instead of class in above example. When, an argument is passed to some_function( )
, compiler generates new
version of some_function()
to work on argument of that type.Example of Function Template
/* C++ program to display larger number among two numbers using function templates. */
/* If two characters are passed to function template, character with larger ASCII value is displayed. */
#include <iostream>
using namespace std;
template <class T>
T Large(T n1, T n2)
{
return (n1>n2) ? n1:n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout<<"Enter two integers: ";
cin>>i1>>i2;
cout<<Large(i1, i2)<<" is larger.";
cout<<"\n\nEnter two floating-point numbers: ";
cin>>f1>>f2;
cout<<Large(f1, f2)<<" is larger.";
cout<<"\n\nEnter two characters: ";
cin>>c1>>c2;
cout<<Large(c1, c2)<<" has larger ASCII value.";
return 0;
}
OutputExplanation
In this program, data of three different types: int, float and char is passed to function template and this template returns the larger of two data passed. In function template data type is represented by name:
T
in above example. During run-time,
when integer data is passed to template function then, compiler knows the type
to use is int. Similarly, when floating-point data and char data is passed, it
knows the type to use is float and char respectively. After knowing the
information of a type, it generates the specific version of Large( )
to work for that type.Example to Swap Datas Using Concept of Templates
/* C++ program to swap datas entered by user. */
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1=1, i2=2;
float f1=1.1, f2=2.2;
char c1='a', c2='b';
cout<<"Before passing data to function template.\n";
cout<<"i1="<<i1<<"\ni2="<<i2;
cout<<"\nf1="<<f1<<"\nf2="<<f2;
cout<<"\nc1="<<c1<<"\nc2="<<c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout<<"\n\nAfter passing data to function template.\n";
cout<<"i1="<<i1<<"\ni2="<<i2;
cout<<"\nf1="<<f1<<"\nf2="<<f2;
cout<<"\nc1="<<c1<<"\nc2="<<c2;
return 0;
}
OutputBefore passing data to function template.
i1=1
i2=2
f1=1.1
f2=2.2
c1=a
c2=b
After passing data to function template.
i1=2
i2=1
f1=2.2
f2=1.1
c1=b
c2=a
C++ TUTORIALS
http://www.cstutoringcenter.com/tutorials/cpp.php
DOWNLOAD ALL THE SOURCE CODE FOR EVERY TUTORIAL EXAMPLE HERE (Zip file).
- Tutorial 1
Some basics - Some elementary topics of C++ which include an introduction to strings, basic input and output with C++ and some library information.
- Tutorial 2
Variables - An introduction to working with variables in C++. It includes the numerous types such as an integer, character, boolean etc. as well as declarations and initializations.
- Tutorial 3
Decision Making & Logic - A detailed look at some logic units of C++ which include the logical operators, if statements, if/else statements and an introduction to a while statement.
- Tutorial 4
Looping - An introduction to a for loop in C++. This includes some examples of triangle stars and squares as well as a bit more detail for a while statement.
- Tutorial 5
Functions - The detailed look at what a function is in C++. This tutorial will demonstrate numerous examples of writing and declaring functions in addition to covering parameters (passing by value or passing by reference).
- Tutorial 6
Intro to Recursion - A brief introduction to recursion in C++. Includes the "factorial" example as well as a trace of that program.
Intermediate
DOWNLOAD ALL THE SOURCE CODE FOR EVERY TUTORIAL EXAMPLE HERE (Zip file).
- Tutorial 7
Arrays - Fundamentals of arrays in C++. This examines how it looks in memory in addition to covering the one and two dimensional array. Also involves some more practice with looping.
- Tutorial 8
Strings - Different features of strings in C++ including manipulating, functions, length, replace and find.
- Tutorial 9
File Input/Output - Manipulating text files in C++ for both input and output purpose.
- Tutorial 10
Character Sequences - Shows how to use a character array and characters in C++.
- Tutorial 11
C++ Pointers - Introduction to a pointer in C++. Shows how to use them and why they are used. Topics include addresses and dereferencing.
Advanced
DOWNLOAD ALL THE SOURCE CODE FOR EVERY TUTORIAL EXAMPLE HERE (Zip file).
- Tutorial 12
Classes & Objects I - Introduction to classes in C++. Shows how to declare a class, use accessors and mutators in addition to constructors.
- Tutorial 13
Classes & Objects II - Continuation of Tutorial 12, this time featuring more detail on member functions, operator overloads and the this keyword.
- Tutorial 14
Templates - Covers the basics of a C++ template to a class, struct and function.
- Tutorial 15
Other Data Types - Other data types of C++ are discussed here including a struct, typedef and the introduction to the arrow operator -> when dealing with pointers.
- Tutorial 16
Dynamic memory - Dynamic memory allocation is covered which uses the new, new[], delete and delete[] operators.
Data Structures
DOWNLOAD ALL THE SOURCE CODE FOR EVERY TUTORIAL EXAMPLE HERE (Zip file).
- Tutorial 17
Linked Lists - Shows a simple linked list making use of classes and templates. Shows how to declare a node, use accessors and mutators in addition to printing a linked list.
- Tutorial 18
Stacks - Shows a simple stack in C++. Makes use of a class and templates. Also shows pushing and popping data.
Miscellaneous
DOWNLOAD ALL THE SOURCE CODE FOR EVERY TUTORIAL EXAMPLE HERE (Zip file).
- Tutorial 19
Random Numbers - C++ tutorial on generating random numbers. Shows the use of two C++ libraries <cstdlib> and <ctime>. Covers srand as well and shows a few examples of random numbers.
- Introduction to C++ Programming
- http://www.cs.armstrong.edu/liang/cpp/
- Part I Fundamentals of ProgrammingPart II Object-Oriented ProgrammingPart III Data Structures and Advanced Topics
Very good information and thanks for posting this here! Please keep sharing more information like this further in future. You can find more information on C++ Tutorials in the following link.
ReplyDeleteLearn Cpp online