Showing posts with label Advance C. Show all posts
Showing posts with label Advance C. Show all posts

TEMPLATES IN C++



Templates are the foundation of generic programming which involves writing code in a way that is independent of any particular type.

Hello Friends Today I am going to learn about Template in C++. That how to use Template inn C++. A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators, and algorithms are examples of generic programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector or vector .
You can use templates to define functions as well as classes, let us see how do they work:
Function Template: The general form of a template function definition is shown here:
template ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.
The following is the example of a function template that returns the maximum of two values:
#include
#include
using namespace std;
template
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}

If we compile and run above code, this would produce following result:
Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World

Class Template:
Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:
template class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push and pop the elements from the stack:
#include
#include
#include
#include
#include
using namespace std;
template
class Stack {
private:
vector elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const{ // return true if empty.
return elems.empty();
}
};
template
void Stack::push (T const& elem)
{
// append copy of passed element
elems.push_back(elem);
}
template
void Stack::pop ()
{
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
template
T Stack::top () const
{
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main()
{
try {
Stack intStack; // stack of ints
Stack stringStack; // stack of strings
// manipulate int stack
intStack.push(7);
cout << intStack.top() < // manipulate string stack
stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (exception const& ex) {
cerr << "Exception: " << ex.what() < return -1;
}
}
If we compile and run above code, this would produce following result:
7
hello
Exception: Stack<>::pop(): empty stack
I think this post will help you.I think this post will help you.
Thanks!!!
If any query about this post then put your comment in comment box below..

POLYMORPHISM IN C++



Hello Friends !!!! Today I am going to explain about the Polymorphism in C++.The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes:
#include
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" < return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :" < return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :" < return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
When the above code is compiled and executed, it produces following result:
Parent class area
Parent class area
The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this:
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" < return 0;
}
};
After this slight modification, when the previous example code is compiled and executed, it produces following result:
Rectangle class area
Triangle class area
This time the compiler looks at the contents of the pointer instead of it's type. Hence since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called.
As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations.
Virtual Function: A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding.
Pure Virtual Functions: It's possible that you'd want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class.
We can change the virtual function area() in the base class to the following:
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function.

I think this post will help you.I think this post will help you.
Thanks!!!
If any query about this post then put your comment in comment box below...

STRUCTURE IN C++



Hello Friend!!! Today I am going to learn about Structure in C++.What is Structure and how they Used ? In C++ Not big diff between class and Structure Class have data and function present in it but structure has only data member in it.Data items in a structure is called data member. So Let's See an example of Structure in C++ :
#include
struct Part //Declaring of a Structure//
{
int modelno; //ID model no.//
int partno;
float cost;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
Part p1; //Define Structure//
p1.modelno=62;
p1.parto=23;
p1.cost=21.55;
///////Display Structure Members////////////
cout<<"model number"< cout<<"part number"< cout<<"cost is"< return 0;
}
I think this post will help you.I think this post will help you.
Thanks!!!
If any query about this post then put your comment in comment box below...

INHERITANCE IN C++


Hello Friends !!! Now I am going to explain inheritance in C++.One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base & Derived Classes:
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows:

#include
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;
}
When the above code is compiled and executed, it produces following result:
Total area: 35
Access Control and Inheritance:

A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.We can summarize the different access types according to who can access them in the following way:
Access public protected private
Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no
A derived class inherits all base class methods with the following exceptions:
Constructors, destructors and copy constructors of the base class.
Overloaded operators of the base class.
The friend functions of the base class.
Type of Inheritance:

When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above.We hardly use protected or private inheritance but public inheritance is commonly used. While using different type of inheritance, following rules are applied:
Public Inheritance:

When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
Protected Inheritance:

When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
Private Inheritance:

When deriving from a private base class, public and protected members of the base class become private members of the derived class.
Multiple Inheritances:

A C++ class can inherit members from more than one class and here is the extended syntax:
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example:
#include
using namespace std;
// Base class Shape
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Base class PaintCost
class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
// Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}
When the above code is compiled and executed, it produces following result:
Total area: 35
Total paint cost: $2450

I think this post will help you.
Thanks!!!
If any query about this post then post your comment below...

ENVIROMENTAL SETUP FOR C++


Hello Friends!!! Now I am learn that how can you setup a best enviroment for learn C++ programming language.Before you start doing programming using C++, you need following two software's available on your computer.

Text Editor:=>
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.Name and version of text editor can vary on different operating systems. For exampe Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or Unix.The files you create with your editor are called source files, and for C++ they typically are named with the extension .cpp, .cp, or .c.Before starting your programming, make sure you have one text editor in place and you have enough experience to type your C++ program.


C++ Compiler:=>
This is actual C++ compiler which will be used to compile your source code into final executable program.Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .cpp by defaultMost frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have respective Operating Systems.

Installing GNU C/C++ Compiler:=>
Unix/Linux Installation: If you are using Linux or Unix then check whether GCC is installed on your system by entering the following command from the command line:
$ g++ -v If you have installed GCC then it should print a message such as the following: Using built-in specs. Target: i386-redhat-linux Configured with: ../configure --prefix=/usr ....... Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at http://gcc.gnu.org/install/

Mac OS X Installation:=>
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions.Xcode is currently available at developer.apple.com/technologies/tools/.

Windows Installation:=>
To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-.exe.While installing MinWG, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names.When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.
I think this post will help you.
Thanks!!!.
If still you have any query then post your comment below...

OBJETS , CLASSES IN C++


Hello Friends!!!. Now I am going to tell You about the objets,classes in C++ language.When we consider a C++ program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instant variables mean. 1.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. 2.Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. 3.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. 4.Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables.


Let us look at a simple code that would print the words Hello World.
#include using namespace std;
// main() is where program execution begins.
int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look various parts of the above program:
The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header is needed.The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.The next line // main() is where program execution begins. is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.The line int main() is the main function where program execution begins.The next line cout << "This is my first C++ program."; causes the message "This is my first C++ program" to be displayed on the screen.The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.

Lets look at how to save the file, compile and run the program. Please follow the steps given below:
Open a text editor and add the code as above.
Save the file as : hello.cpp
Open a command prompt and go to the directory where you saved the file.
Type 'g++ hello.cpp ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
Now type ' a.out' to run your program.
You will be able to see ' Hello World ' printed on the window.
$ g++ hello.cpp
$ ./a.out
Hello World
Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.
You can compile C/C++ programs using makefile.

Semicolons & Blocks in C++.=>
In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.For example, following are three different statements:
x = y;
y = y+1;
add(x, y);
A block is a set of logically connected statements that are surrounded by opening and closing braces. For example:
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where on a line you put a statement. For example:
x = y;
y = y+1;
add(x, y);
is the same as
x = y; y = y+1; add(x, y);

C++ Identifiers:=>
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9). C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case sensitive programming language.Thus Manpower and manpower are two different identifiers in C++. here some examples:
mohd,zara,abc,move_name,a_123.
And also some keywords as same as in C language.
I think this post will help you.
Thanks!!!.
If still you have any query then post your comment below.I will 100% surely help you.

INTRODUCTION TO C++


Hello Friends !!!. Now I am going to tell about the C++ programming language devloped after C Language.C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.This reference will take you through simple and practical approach while learning C++ Programming language.C++ is devloped with advance features related to C language.C++ fully support object oriented language because of four main reason including in it.

1.Data Encapsulation. 2.Data Hiding. 3.Inheritance. 4.Polymorphisum.
The most important thing to do when learning C++ is to focus on concepts and not get lost in language technical details.The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones.C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining runtime and space efficiency.C++ is used by hundreds of thousands of programmers in essentially every application domain.C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under realtime constraints.C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts.Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++.
I think this post will help you.
Thanks!!!
If any query about this post then plzz comment below I will 100% help you.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites