Professional Documents
Culture Documents
CPP Starting Notes
CPP Starting Notes
C Programming language was been developed in the Bells Labs in the year 19691973. UNIX Operating system was also been developed at the same time. In the year 1983 Bjarne Stroustrup created the C++ in the Bells Labs.
Brief History
C++ is an extension of the C Programming Language. C Programming language was been developed in the Bells Labs in the year 1969-1973. UNIX Operating system was also been developed at the same time. Bjarne Stroustrup created the C++ during the year 1983 in the Bells Labs. It was designed for the UNIX environment. It also represents the C programming enhancement and makes programmers to improve the quality of code that has been produced, This makes the code which can be reused easier to write
Assembly level Programming language. It makes it possible to get down into a low-level programming language for the programmers and also tunes as needed. There is a strict control over the memory management for a C++ programmer. C++ have national standards (ANSI). C++ is national standards language. A C++ code written which confirms to national standards can be easily integrated with the existing code. This will also allow the programmer to reuse common libraries. So these common functions need not be written more than once. An dalso note that these functions will behave uniquely wherever they are used. C++, a reusable and object-oriented language Since C++ is an object oriented language, it will make coceptually programming easier. If the object paradigm is learned once, it will allow reuse of code, or part of it through inheritance. The C++ is widely been used and taught Because of this, C++ is a very widely used programming language. there are many tools which are available for the C++ programming, and there is broad base of the programmers contributing to C++ "community".
Inheritance
Generally speaking, objects are been defined in terms of the classes. We know lot about object by knowing about its class. Even if you do not know what the penny-farthing is, if I tell you it was bicycle, you would definately know that it has two wheels, handle bars and the pedals. The Object-oriented systems will take this step further and will allow the classes to be defined in terms of the other classes. For an example, a mountain bikes, race bikes and the tandems are all a different kind of the bicycles. In an object-oriented terminology, the mountain bikes, the race bikes and the tandems are all subclasses of a bicycle class. Similarly, bicycle class is a superclass of the mountain bikes, race bikes and the tandems.
Inheritance Benefits
Subclasses provides the specialized behaviours from a basis of the common elements provided by a superclass. Through use of the inheritance, programmers can reuse a code in superclass many times. Programmers can implement the superclasses that will define the "generic" behaviours (called the abstract classes). Essence of superclass is defined and can be partially be implemented but much of the class is been left undefined and also unimplemented. Other programmers fill in details with the specialized subclasses.
Multiple inheritances
A subclass having more than one superclass is called Multiple inheritances. This will enables a subclass to inherit the properties of more than one super class and to combine all these properties.
Polymorphism
Different types of objects which respond distinctively to same message is called Polymorphism, example, when we do send same message, cost to the spike-bicycle object, a mono-cycle object and the tandem bicycle object, each of these object will respond appropriately. All these cycles of a class bicycle have their own individual price.
Data abstraction
Public interface, formed by a collections of messages understood by the object, will define how to use this object. The programs which wants to manipulate the object, will only have to be concerned about messages this object will understand, and need not worry about how the tasks are achieved nor internal structure of an object. Hiding up of the internal details makes the object abstract, and a technique is normally known as
Encapsulation
Packing up an object's variables within its methods is called encapsulation. Encapsulating the related variables and methods into neat software bundle seems simple but is a powerful idea that provides two benefits to the software developer:
Modular programming-- The source code for any of the object can be written and maintained independently from those of the source code written for other objects. Also, an object can be easily used passing around in the system. For example you can give your bicycle to someone else and it will still work for them too. Information hiding-- An object has a public interface by which other objects can communicate with it. But on the other hand objects can maintain private information and methods that cannot be communicated to others.
To prepare next section, create a new text file and save this code into the file. If you are using unix machine, save a file with a filename hello.C (.C is a file extension). If you using Windows machine, save file with a filename hello.cpp.
stands for the "end-line"). return 0; Since the return type of main is int This line of code is necessary. Let us see about the functions and the return types later, for now understand that the function's return type is an integer type, the function should return an int. return 0; will simply returns 0.
What is Variable?
Variable is the place to store the piece of information. As one might store the friend's phone number in own memory, we can store this information in the computer's memory. These are the means of accessing the computer's memory. There are fairly strict rules on how the variables are named which C++ imposes:
Variable names should start with the letter. The variable names are case-sensitive (i.e., variable "myNumber" is different from "MYNUMBER" which inturn is different from "mYnUmBeR"). Variable names cannot have blank spaces in between. A variable names cannot have the special characters.
Variable types
Variables are of three basic types which are as follows: 1. int 2. float 3. char
Variable type is nothing but a description of the kind of the information a variable will store. Declaring the variable in C++ is simple. Let us say that we want to declare the variable of type int called "myAge". That is to say, Variable myAge will store the integer, Variable myName will store an character, Variable myHeight will store float value. In C++, this is written as shown below: int myAge; char myName; float myHeight;
Boolean Operators
and: && operator //suppose that San is tired bool sanIsTired = true; //but San doesn't have to wake up early bool sanMustWakeUpEarly = false; //will San go to sleep now? bool bedTime = sanIsTired && sanMustWakeUpEarly;
What will this chunk of the code do? It initializes the variables, sanIsTired to true and sanMustWakeUpEarly to false, The third line of code (comments not included), we determine that San is going to sleep if and only if "and" operation is true -- that is, if both the inputs to "and" operation are true. In this case, first input is true and second input is false. Since the "and" requires both inputs to be true in order for output to be true, but one of an inputs is false, output will become false. So, variable bedTime will store a false value.
not: !
"not" operator is used by placing symbol "!", before the boolean value. //suppose that Julie stayed up late bool julieStayedUpLate = true; //will Julie be peppy tomorrow? bool julieIsPeppy = !julieStayedUpLate; This code illustrates the "not" operation. At the end of the code, variable julieIsPeppy will take an opposite value of julieStayedUpLate. If julieStayedUpLate were false, then the variable julianIsPeppy would be true. In this case, opposite is true, so the julieIsPeppy gets the value false.
These operators probably look familiar with an exception of mod (%) operator. Mod is simply a remainder produced by dividing the two integers. In example shown in the table above, if we treat a 10 / 6 as the integer divison, quotient is 1 (rather than being 1.666) and remainder is 4. Hence, a variable remainder will get a value 4.
Equality Operators
An equality operator is used to tests the condition like "is less than", "is greater than", and "is equal to". it is useful to to compare two numbers using the expressions like "x<y". name is less than is greater than is equal to is less than or equal to is greater than or equal to is not equal to symbol sample usage < > == <= >= != bool result = (4 < 7) bool result = (3.1 > 3.1) bool result = (11 == 8) bool result = (41.1 <= 42) bool result = (41.1 >= 42) bool result = (12 != 12) result true false false true false false
Once using the equality operator is known,it is easy to use all the others. They all will work in the same way: they take an expressions on the either side of them, and will either returns true or false.
name boolean not multiplication division mod addition subtraction is less than is less than or equal to
is greater than is greater than or equal to is equal to is not equal to boolean and boolean or assignment multiply and assign divide and assign mod and assign add and assign subtract and assign
A branching statement
A branching statement is one which divides the code into certain number of branches depending upon some coditions specified. Example for branching statement is the If statement. if (x > 0) cout<<x is positive integer; else cout<<x is negitive integer; Depending on the condition certain series of events will be executed.
Another example for branching statement is a switch statement. Let us study switch statement later. Here in the code given above will checks the condition if x is greater than "0" or not. if it is greater then prints x is a positive number otherwise prints x is a negitive number.
This is the loop statement. A line of code or the block of code is been executed for certain number of times as specified in the for statement. There are three parameters in the for statement. First intialization, second condition and finally increement statement. for(i=0;i<5;i++) cout<<i; A for statement execute a code for specified number of times. In this instance it executes 5 times. It executes until the condition "i<5" fails.
What is Function?
A functions allows to group the series of steps under single name. Basic form of the function definition is as follows:
output function_name (input_1, input_2, input_3, input_...) { // code to execute inside function } It is called the function definition as we are defining function. We say that This is a function called function_name, with the inputs input_1, input_2, etc., and whose output is the output. When this function is called, function will execute a block of code in between the curly braces "{" and "}". Here is the syntax for the function.
return_type function_name (parameter_1, parameter_2, parameter_3, parameter_...) { // code to execute inside function }
Notice in the place of output, function definition says the return_type. That is because when we actually are writing the function definition, we will put an return type there, immediately preceding name of a function. Return type is nothing but a plain old variable type, such as the int, or double, etc. Similarly the parameters use the variable types too. If first input to the function is the int, then first parameter will be something like int myNumber.
A Member Data
A class player can have attributes like health,strength, ability etc. These attributes of a class are called memeber data. These can be either private, public or protected Private members are those which can only be accessed by the member funtions where as the Public members can be
A Member Function
Player object can have the behavours like Move, AttackMonster and GetTreasure. Till now we mentioned what a player can do and not how the Player can execute these functions. We need to write the function body for each of the function, so that a Player instance will come to know how to attack the monster, Here is a syntax for writing the function definition for the member function: void Player::move() { //function body goes here } It is almost similar to writing the function definition for the plain-old, stand-alone functions. Only difference here is that we do precede the name of a function, with the object name here move(), with the Player object, and a scope resolution operator :: which tells a compiler that this function is the part of the Player class.
Instantiating an Object
Creating an object is similar to creating a simple variable. Let us say assume that we want four players in the game, each of them trying to find their way to end of the maze faster than the other player. This can be done by creating four instances of Player object as shown below. Player Player Player Player blueHat; redHat; greenHat; yellowHat;
Though all these objects are Players, they are independent from one another. They are created by a same template, but they do have some different attributes. Take for example, "blueHat" may be a slow and strong player, while a "greenHat" may be quick but weak, and an "yellowHat" may be well balanced individual, etc. Things which will make
these objects similar is they all should have the values for a strength, health, and the ability. but they all are different as each of them can each have their own values for these attributes. So an object is intantiated or created by prefixing a class name to the object name as shown above.
Objects
Object is a component of the program which knows how to carry out some actions and interact with other pieces of a code. Functions which previously have been described as the "black boxes" takes the input and spit out the output. An objects can be thought as a "smart" black boxes. which know how to do more than one specific action, and also they can store own set of data. Designing the program with an object allows the programmer to model a program after a real world. Player Object: data: health strength ability actions: move attack monster get treasure END; Here is a "Player" object. This object have attributes healthh, strength
and ability. These attributes in terms of Programming language are called as data members. The various actions that a player oject can perform are move, attakMonster and getTreasure, These actions are called memeber Functions.
Constructors
Objects need to initialize the variables or assign the dynamic memory to them during their creation to become operative and to avoid the returning unexpected values during execution. To avoid this, a class can include special function "constructor", which is been automatically called when the new object of the class is created. The constructor function should have same name as that of the class, and cannot have the return type not even the void. Here we have implemented the CRectangle class including the constructor: // example: class constructor #include <iostream> using namespace std;
class CRectangle { int width, height; public: CRectangle (int,int); int area () { return (width*height); } }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Here the constructor initializes the values of x and y with parameters which are passed to it.
Destructors
A destructor fulfills opposite functionality. This is automatically been called when the object is been destroyed, because the scope of existence has finished off or due the reason that it is object which is dynamically assigned and it is released using delete operator. A destructor should have same name as that of class, but prefixed with tilde sign (~) and it should not return any value. Use of the destructors is suitable especially when the object assigns the dynamic memory during lifetime and at the moment the object is destroyed we want to free the memory which was allocated to the object. // example on constructors and destructors #include <iostream> using namespace std; class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () { return (*width * *height); } }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () {
delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }
Class Pointers
Perfectly it is valid to create the pointers which point to the classes. Simply we have to consider, after declaration, a class will become valid type, so we can make use of the class name as a type for pointer. Take for example: CRectangle * prect; This is the pointer to object of the class CRectangle. As with data structures, in order to refer to member of an object pointed by the pointer directly, we can use an arrow operator (->) of the indirection. Consider the following example. // pointer to classes example #include <iostream> using namespace std; class CRectangle { int width, height; public: void set_values (int, int); int area (void) {
return (width * height); } }; void CRectangle::set_values (int a, int b) { width = a; height = b; } int main () { CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b->set_values (3,4); d->set_values (5,6); d[1].set_values (7,8); cout << "a area: " << a.area() << endl; cout << "*b area: " << b->area() << endl; cout << "*c area: " << c->area() << endl; cout << "d[0] area: " << d[0].area()<< endl; cout << "d[1] area: " << d[1].area() << endl; return 0; }
Overloading
Overloading in C++ advocates simplicity in usage and the readability. Therefore all forms of the operators are overloaded to give a natural and the domain oriented meanings. An increment operator "++" can be called in two different forms as the post fix and the pre fix operator. Programmers do have some difficulty in overloading or using it, as they dont know how to differentiate between them. That is why the postfix operators are been created with the dummy parameter of a integer type. Prefix operator "++" can be overloaded like the postfix operator without
making any change. Look at the following function definition. Class Test { int i; public: void operator ++() { ++i; } }; The post fix ++ operator will be overloaded with a dummy integer parameter as follows. Class Test { int i; public: void operator ++(int) { i++; } };
Friend Function
The data taht is declared as private inside the class cannot be accessed from outside a class. The function which is not the member function or the class which is external can never access these private data. But there may also be some of the cases, where the programmer needs access to private data, either from the non-member functions and the external classes. C++ will offer some of the exceptions in these cases.
Once the non-member function is been declared as friend, it can get access to the private data of a class. similarly when the class is been declared as friend, friend class can have the access to private data of a class which made this as a friend
#include <iostream.h> //Declaration of the function to be made as friend for the C++ Tutorial sample int AddToFriend(int x); class CPP_Tutorial { int private_data; friend int AddToFriend(int x); public: CPP_Tutorial() { private_data = 5; } }; int AddToFriend(int x) { CPP_Tutorial var1; return var1.private_data + x; } int main() { cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<<endl; }
A Friend Class:
Declaring a friend class is also same, The only different thing is class definition is bit different. #include < iostream.h > class CPP_Tutorial { int private_data; friend class friendclass; public: CPP_Tutorial() { private_data = 5; } }; class friendclass { public: int subtractfrom(int x) { CPP_Tutorial var2; return var2.private_data - x; } }; int main() { friendclass var3; cout << "Added Result for this C++ tutorial: "<< var3.subtractfrom(2) }
Virtual Function
Virtual function is a function which is a member of a class, the functionality of which can be over-ridden in the derived classes. It is declared as a virtual in the base class using the keyword virtual. Virtual nature is been inherited in the subsequent derived classes and there is no need to re-state virtual keyword. Whole function body can be replaced by the new set of implementation in a derived class. The code given below shows how virtual function in C++ can be used to achieve the dynamic or the runtime polymorphism. #include <iostream.h> class base { public: virtual void display() { cout<<\nBase; } }; class derived : public base { public: void display() { cout<<\nDerived; } }; void main() { base *ptr = new derived(); ptr->display(); } In the example above, pointer is of the type base but it points to derived class object. A display() method is virtual in the nature. Therefore to resolve a virtual method call, context of a pointer is been considered, Which means that a display method of derived class is been called and not the base class. If a method was non virtual in nature, a display() method of base class might have been called up.
{ ... ... } Here the exception is the defined class with the constructor with no parameters been passed. It will be useful to have the info on what type of error has occurred. This can be done by two methods. Either can define the different exception-classes and then throw them according to the error been occurred. Or can give a class parameter containing error message and allow a class to display the message.
Template functions
The C++ Function templates are the functions that can handle a different data types without any separate code for all of the datatypes. For the similar operation on the several kinds of the data types, the programmer may need not write the different versions by function overloading. C++ template based function is enough, it will take care of all data types. Let us cosider a small example for the Add function. If requirement is to
use the Add function to both types that is an integer and float type, then the two functions needs to be created for each data type. int Add(int a,int b) { return a+b; } // function Without C++ template float Add(float a, float b) { return a+b; } // function Without C++ template If the data types are more than two then it is difficult to be handled, Because those many number of functions are to be added. If we make use of the c++ function template, whole process will be reduced to the single c++ function template. Here is the code fragment for the Add function. template <class T> T Add(T a, T b) //C++ function template sample { return a+b; }
//Sample code snippet for C++ Class Template template <typename T> class MyQueue { std::vector data; public: void Add(T const &d); void Remove(); void Print(); };
What is C++?
C++ is an extension of the C Programming Language. C Programming language was been developed in the Bells Labs in the year 1969-1973. UNIX Operating system was also been developed at the same time. Bjarne Stroustrup created the C++ during the year 1983 in the Bells Labs. It was designed for the UNIX environment. It also represents the C programming enhancement and makes programmers to improve the quality of code that has been produced, This makes the code which can be reused easier to write
What is Inheritance?
Generally speaking, objects are been defined in terms of the classes. We know lot about object by knowing about its class. Even if you do not know what the penny-farthing is, if I tell you it was bicycle, you would definately know that it has two wheels, handle bars and the pedals. The Object-oriented systems will take this step further and will allow the classes to be defined in terms of the other classes. For an example, a mountain bikes, race bikes and the tandems are all a different kind of the bicycles. In an object-oriented terminology, the mountain bikes, the race bikes and the tandems are all subclasses of a bicycle class. Similarly,
bicycle class is a superclass of the mountain bikes, race bikes and the tandems.
Inheritance Benefits
Subclasses provides the specialized behaviours from a basis of the common elements provided by a superclass. Through use of the inheritance, programmers can reuse a code in superclass many times. Programmers can implement the superclasses that will define the "generic" behaviours (called the abstract classes). Essence of superclass is defined and can be partially be implemented but much of the class is been left undefined and also unimplemented. Other programmers fill in details with the specialized subclasses.
What is Polymorphism?
Different types of objects which respond distinctively to same message is called Polymorphism, example, when we do send same message, cost to the spike-bicycle object, a mono-cycle object and the tandem bicycle object, each of these object will respond appropriately. All these cycles of a class bicycle have their own individual price.
achieved nor internal structure of an object. Hiding up of the internal details makes the object abstract, and a technique is normally known as the data abstraction.
What is Encapsulation?
Packing up an object's variables within its methods is called encapsulation. Encapsulating the related variables and methods into neat software bundle seems simple but is a powerful idea that provides two benefits to the software developer.