CPP Beginners

Embed Size (px)

Citation preview

  • 8/8/2019 CPP Beginners

    1/26

    C++ Tutorial. For Beginners(Taken from http:// cpp-tutorial.cpp4u.com/index.html)

    This usage-oriented online C++ tutorial is intended to help you get your C++ experience on

    the right foot. Using some Macromedia Flash animations where needed, you will find here allthe required information to get efficiently started on your usage of C++ language, independentlyof the platform you are planning to use it on. After a short introduction aimed at getting youstarted with the required tools to write and build C++ code source into executable binaries, youwill get thrown into the basics of C++ and its control structures, as an algorithmic starting point.Still oriented on the usability, you will be pointed, along with detailed explanations, to the C-stylestandard functions that can be used in your C++ source code to easien usual tasks. The tutorialwill then lead you into the Object Oriented paradigm on C++ language, which will be a must-have in order to understand all the STL(Standard Template Library)-related info that you will findin the last part of this tutorial.

  • 8/8/2019 CPP Beginners

    2/26

    // This is my first C++ program//It prints a line of text# include int main(){std::cout

  • 8/8/2019 CPP Beginners

    3/26

    closing brace ( } ) mark the beginning and end of a function. Anything which is inside the bracesis the body of that function.In our example, the function body consists of only two statements,{std::cout

  • 8/8/2019 CPP Beginners

    4/26

    Return StatementLast line in the body of our first program is

    return 0;

    The keyword return is a special statement which is used to exit a function and return a value.This statement exits the function main indicating its completion and returns the value 0 to the

    operating system indicating that the program successfully ran to completion. return statement isincluded at the end of every main function.

    OutputWhen this program is run, it prints the following output

    My first C++ program

    For programs to do exciting things, they should be written, compiled and then run on a computerusing a compile or IDE. Next tutorial, How to compile and run programs shows how to runprograms.

    Congratulations!! You have just run your first C++ program and have understood many important

    features of C++.

    2.0 HOW TO WRITE AND COMPILE C++ PROGRAMS

    In order to run a program and see it doing wonderful things, you should first write the program.The program can be written in any text editor, such as vi and emacs in Unix environment andusing command prompt in DOS. There are also several Integrated Development Environment(IDE) packages available which provide a complete programming environment for C++ in whichyou can write, compile, run, and debug your program.

    C++ programs are saved with extensions .C, .cc, .cpp, .cxx depending on the platform you are

    working upon.Once you have saved a program, next stage is compiling it using a compiler which convertsyour C++ program into the object code which the computer can understand.

    Compile using g++ compilerIf you are using UNIX environment and using g++ compiler, then compiling your C++ program issimple. After you have saved the program file, simply type the command

    g++ program.cc o program

    where program is the name of the program. For example the name of our first program is first,then save it using extension first.cc. To compile, type

    g++ first.cc o first

    To run the program, type first or ./first at the command prompt and your program will run.

    Compile using DevC++ compilerIf you work on Windows and use DevC++, then editing and compiling is as easy as click of abutton. DevC++ is an IDE which allows you to edit, compile, run and debug your program in theIDE itself. If you want to install DevC++ then install it from

    http://prdownloads.sourceforge.net/dev-cpp/devcpp4980.exe.

  • 8/8/2019 CPP Beginners

    5/26

    1. Once you have installed and configured the software, Write and save your programusing DevC++ itself. Create a new program by clicking on New - Project.

    2. Choose Empty Project from New Project dialog and choose a name for the program, inour case first and click Ok.

    3. Write the code of the program and save it.

  • 8/8/2019 CPP Beginners

    6/26

    4. Click on Compile button (third row, first button) to compile your source code. If there areany errors in your program, then a window at the bottom will specify the warnings.

    5. After program is compiled, click on Run button (next to compile).6. However, DevC++ has a problem. As soon as you Run the program, output window

    opens momentarily and then it closes. So to come around this solution, set a breakpointat the end of main function and then click on Debug instead of running it.

    7. When you run the program, output window will show the string.

  • 8/8/2019 CPP Beginners

    7/26

    3.0 OOP FEATURES

    Classes and objects and Methods and propertiesA class is a user defined data type like a structure or a union. A class consists of data variablesand functions. These variables and functions are called members of the class. The variablesare called data members and functions are called member functions. The member functions arealso called methods. The data members are called properties of the class. An object is theinstance of the class. An object is like a compound variable of the user defined type. It links bothcode and data. Within the object, members of the class can be public or private to the object.The declaration of a class is syntactically same as structure. The class is declared usingkeyword class.

    The general form of the declaration of the class is:-

    class class_name{

    access_specifier:data functions

    access_specifier:data functions

    } object_list;

    The object_list is optional. The object_list is used to declare objects of the class. Theclass_name is the name of the class. The access_specifier can either public , private orprotected . The members of the class by default are private to the class. If theaccess_specifier is private then members of the class are not accessible outside the class.If the access_specifier is public then members of the class can be accessed from outsidethe class. The protected access_specifier is needed at the time of inheritance. Themembers can be accessed using an objects name, a dot operator and name of the member.Here is a program which shows how classes and objects are created.

    #includeusing namespace std;

    class cube{

    public:double side;

    double volume(){

    return(side*side*side);}

    };

  • 8/8/2019 CPP Beginners

    8/26

    int main(){

    double volume1=0;cube c1,c2;cout c1.side;cout

  • 8/8/2019 CPP Beginners

    9/26

    equates the side of object c2 to side of object c1 increased by 2. The objects c2 and c1 aredifferent. The statement

    cout

  • 8/8/2019 CPP Beginners

    10/26

    int main(){

    cube c1(2.34);cube c2;cout

  • 8/8/2019 CPP Beginners

    11/26

    The statementscout

  • 8/8/2019 CPP Beginners

    12/26

    double len(){

    return(length);}rectangle(double lenght1,double breadth1){

    length=lenght1;breadth=breadth1;

    }};

    int main(){

    rectangle r1(3.5,4.6);double a=r1.len();double b=r1.breadth;cout

  • 8/8/2019 CPP Beginners

    13/26

    declares an object r1 of rectangle. The constructor initializes the length and breadth of theobject as soon as it is created. The statement

    double a=r1.len();

    returns the length of the object. The data member length cannot be accessed directly as it isdeclared private therefore member function len() is used to return the value of length. Thestatement double a=r1.length in main() function is invalid as data member length isinaccessible. The statement

    double b=r1.breadth;

    equates the value of b to the value of breadth of object r1. The statementcout

  • 8/8/2019 CPP Beginners

    14/26

    derived_constructor (argument list): base1 (arg_list)base2(arg_list1)baseN(arg_list)

    The derived_constructor is the name of the derived class. The argument list is list of the datamembers of the derived class. The base1 is name of the base class. The arg_list is the list ofthe members of the base class. Here is a program which illustrates the features of inheritance.

    #includeusing namespace std;

    class shape{

    private :double length;

    protected:double breadth;

    public :double len()

    { return(length);}shape(double length1,double breadth1){

    length=length1;breadth=breadth1;

    }//shape() { }

    };

    class shape1{

    public:double height;shape1(double height1){

    height=height1;}//shape1() { }

    };

    class cuboid : public shape, private shape1{

    public:cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)

    {cout

  • 8/8/2019 CPP Beginners

    15/26

    double bre(){

    return(breadth);}double ht(){

    return(height);}

    };

    int main(){

    cuboid c1(2.4,3.5,6.7);cout

  • 8/8/2019 CPP Beginners

    16/26

    The statements

    double volume(){

    return(height*breadth*len());}

    calculate the volume of the cuboid . The class cuboid cannot access the private data memberlength of the shape class. It access the length by calling the function len() which returns theprivate data member length . The data member breadth becomes the protected member ofthe class cuboid . The height which is public member of shape1 class becomes the privatemember of the class cuboid as it inherits the shape1 class as private. The statements

    double bre(){

    return(breadth);}

    returns thebreadth

    of thecuboid

    as data memberbreadth

    cannot be accessed outside theclass as it is protected member of cuboid . The statement

    double ht(){

    return(height);}

    returns the height of the cuboid as data member height cannot be accessed outside theclass as height is the private data member of the class cuboid . The statement

    cuboid c1(2.4,3.5,6.7);

    creates an object c1 of type cuboid . The constructor is called to initialize the values of thecuboid . The constructor of shape is executed and then constructor of shape1 is executed andthen finally constructor of cuboid is executed. The statement

    cout

  • 8/8/2019 CPP Beginners

    17/26

    6.0 POLYMORPHISM AND VIRTUAL FUNCTIONS

    Polymorphism is defined as one interface to control access to a general class of actions. Thereare two types of polymorphism one is compile time polymorphism and the other is run timepolymorphism. Compile time polymorphism is functions and operators overloading. Runtimetime polymorphism is done using inheritance and virtual functions.

    Function OverloadingPolymorphism means that functions assume different forms at different times. In case ofcompile time it is called function overloading. For example, a program can consist of twofunctions where one can perform integer addition and other can perform addition of floatingpoint numbers but the name of the functions can be same such as add . The function add() issaid to be overloaded. Two or more functions can have same name but their parameter listshould be different either in terms of parameters or their data types. The functions which differonly in their return types cannot be overloaded. The compiler will select the right functiondepending on the type of parameters passed. In cases of classes constructors could beoverloaded as there can be both initialized and unintialized objects. Here is a program whichillustrates the working of compile time function overloading and constructor overloading.

    #includeusing namespace std;

    class employee{

    public:int week;int year;double calculate(double salary){

    return(salary*week);

    }int calculate(int salary){

    return(salary*week*year);}employee(int week1){

    week=week1;}employee(int week1,int year1){

    week=week1;year=year1;

    }};

  • 8/8/2019 CPP Beginners

    18/26

    int main(){

    int sal;double sal2;employee emp1(10);employee emp2(10,3);cout emp1.year;cout

  • 8/8/2019 CPP Beginners

    19/26

    employee(int week1,int year1){

    week=week1;year=year1;

    }

    declare two constructors of class employee where one constructors parameter list is differentfrom other constructors parameter list. The constructor is overloaded. The statement

    employee emp1(10);

    declares an object emp1 of type employee . When object is created first constructor is calledsince the argument list matches with parameter list of the constructor. The constructor initializesthe data member week of the object emp1 . The statement

    employee emp2(10,3);

    declares an object emp2 of type employee . The second constructor is called since the argument

    list matches with the parameter list of the constructor. The constructor initializes the datamembers week and year of the object emp2 . In the statement

    cout

  • 8/8/2019 CPP Beginners

    20/26

    #includeusing namespace std;

    class rectangle{

    public:int length;int breadth;

    rectangle(int length1,int breadth1){

    length=length1;breadth=breadth1;

    }

    int operator+(rectangle r1){

    return(r1.length+length);}

    };

    int main (){

    rectangle r1(10,20);rectangle r2(40,60);int len;len=r1+r2;cout

  • 8/8/2019 CPP Beginners

    21/26

    len=r1+r2;

    calls the operator()+ function to calculate the length of the two objects. The return type is ofinteger. The variable len will contain the total of length of the objects.

    Virtual FunctionsA virtual function is a member function of the base class and which is redefined by the derivedclass. When a derived class inherits the class containing the virtual function, it has ability toredefine the virtual functions. A virtual function has a different functionality in the derived class.The virtual function within the base class provides the form of the interface to the function.Virtual function implements the philosophy of one interface and multiple methods. The virtualfunctions are resolved at the run time. This is called dynamic binding. The functions which arenot virtual are resolved at compile time which is called static binding. A virtual function is createdusing the keyword virtual which precedes the name of the function.

    Virtual functions are accessed using a base class pointer. A pointer to the base class can becreated. A base class pointer can contain the address of the derived object as the derivedobject contains the subset of base class object. Every derived class is also a base class. Whena base class pointer contains the address of the derived class object, at runtime it is decidedwhich version of virtual function is called depending on the type of object contained by thepointer. Here is a program which illustrates the working of virtual functions.

    includeusing namespace std;

    class shape{

    public:int side;

    virtual int volume()

    {cout

  • 8/8/2019 CPP Beginners

    22/26

    class cuboid:public shape{

    public:int breadth;int height;int volume(){

    cout

  • 8/8/2019 CPP Beginners

    23/26

    The program has base class shape and class cube and cuboid which inherits base class. Thebase class has virtual function volume . The statements

    virtual int volume(){

    cout

  • 8/8/2019 CPP Beginners

    24/26

    displays the volume of the cube as s->volume() calls the function volume of the derived classcube . The pointer s contains the address of the object of derived class cube . In the statement

    s=&c2;

    pointer s now contains the address of the derived class object c2 . The statement

    cout

  • 8/8/2019 CPP Beginners

    25/26

    class cuboid:public shape{

    public:int breadth;int height;int volume(){

    cout

  • 8/8/2019 CPP Beginners

    26/26

    The statement

    virtual int volume()=0;

    declares pure virtual function volume() which has no definition. The class shape is nowabstract class and objects of type shape cannot be created.