C Plus Plus Story

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

History of C and C++

C++ evolved from C, which evolved from two previous programming languages, BCPL and B. BCPL was developed in 1967 by Martin Richards as a language for writing operating-systems software and compilers for operating systems. Ken Thompson modeled many features in his language B after their counterparts in BCPL and used B to create early versions of the UNIX operating system at Bell Laboratories in 1970. The C language was evolved from B by Dennis Ritchie at Bell Laboratories. C uses many important concepts of BCPL and B. C initially became widely known as the development language of the UNIX operating system. Today, most operating systems are written in C and/or C++. C is now available for most computers and is hardware independent. With careful design, it is possible to write C programs that are portable to most computers. The widespread use of C with various kinds of computers (sometimes called hardware platforms) unfortunately led to many variations. This was a serious problem for program developers, who needed to write portable programs that would run on several platforms. A standard version of C was needed. The American National Standards Institute (ANSI) cooperated with the International Organization for Standardization (ISO) to standardize C worldwide; the joint standard document was published in 1990 and is referred to as ANSI/ISO 9899: 1990. C++, an extension of C, was developed by Bjarne Stroustrup in the early 1980s at Bell Laboratories. C++ provides a number of features that "spruce up" the C language, but more importantly, it provides capabilities for object-oriented programming. C++ Standard Library C++ programs consist of pieces called classes and functions. You can program each piece that you may need to form a C++ program. However, most C++ programmers take advantage of the rich collections of existing classes and functions in the C++ Standard Library. Thus, there are really two parts to learning the C++ "world." The first is learning the C++ language itself; the second is learning how to use the classes and functions in the C++ Standard Library. Throughout the book, we discuss many of these classes and functions. P J. Plauger's book, The Standard C Library (Upper Saddle River, NJ: Prentice Hall PTR, 1992), is a must read for programmers who need a deep understanding of the ANSI C library functions that are included in C++, how to implement them and how to use them to write portable code. The standard class libraries generally are provided by compiler vendors. Many special-purpose class libraries are supplied by independent software vendors. Typical C++ Development Environment C++ systems generally consist of three parts: a program development environment, the language and the C++ Standard Library. C++ programs typically go through six phases: edit, preprocess, compile, link, load and execute. The following discussion explains a typical C++ program development environment.

My First Program in C++: Printing a Line of Text


// Fig. 2.1: fig02_01.cpp // Text-printing program. #include <iostream> // allows program to output data to the screen function main begins program execution int main() { std::cout << "Welcome to C++!\n"; // display message return 0; // indicate that program ended successfully } // end function main

Welcome to C++!

Escape sequences. Escape Description sequence Newline. Position the screen cursor \n to the beginning of the next line. Horizontal tab. Move the screen \t cursor to the next tab stop. Carriage return. Position the screen \r cursor to the beginning of the current line; do not advance to the next line. Alert. Sound the \a system bell. Backslash. Used to print \\ a backslash character.

Single quote. Use to print \' a single quote character. Double quote. Used to print \" a double quote character.

Program 2. Addition program that displays the sum of two integers entered at the keyboard.
// Addition program that displays the sum of two numbers. #include <iostream> // allows program to perform input and output // function main begins program execution int main() { // variable declarations int number1; // first integer to add int number2; // second integer to add int sum; // sum of number1 and number2 std::cout << "Enter first integer: "; // prompt user for data std::cin >> number1; // read first integer from user into number1 std::cout << "Enter second integer: "; // prompt user for data std::cin >> number2; // read second integer from user into number2 sum = number1 + number2; // add the numbers; store result in sum std::cout << "Sum is " << sum << std::end1; // display sum; end line return 0; // indicate that program ended successfully } // end function main

Enter first integer: 45 Enter second integer: 72 Sum is 117

Equality and relational operators. Standard Meaning C++ Sample equality algebraic of C++ C++ or condition relational condition equality Relational operators or relational operator operator x is greater x > y than y x is less x < than y y x is greater x >= than y or equal to y x is less than x <=or y equal to y Equality operators x is x equal == = y to y x is not x != equal y to y Equality and relational operators.
// Comparing integers using if statements, relational operators // and equality operators. #include <iostream> // allows program to perform input and output using std::cout; // program uses cout using std::cin; // program uses cin using std::endl; // program uses endl // function main begins program execution int main() { int number1; // first integer to compare int number2; // second integer to compare

cout << "Enter two integers to compare: "; // prompt user for data cin >> number1 >> number2; // read two integers from user if ( number1 == number2 ) cout << number1 << " == " << number2 << endl; if ( number1 != number2 ) cout << number1 << " != " << number2 << endl; if ( number1 < number2 ) cout << number1 << " < " << number2 << endl; if ( number1 > number2 ) cout << number1 << " > " << number2 << endl; if ( number1 <= number2 ) cout << number1 << " <= " << number2 << endl; if ( number1 >= number2 ) cout << number1 << " >= " << number2 << endl; return 0; // indicate that program ended successfully } // end function main

Enter two integers to compare: 3 7 3 != 7 3 < 7

3 <= 7

Procedural, Structured, and Object-Oriented Programming


Until recently, computer programs were thought of as a series of procedures that acted on data. A procedure, also called a function or a method, is a set of specific instructions executed one after the other. The data was separate from the procedures, and the trick in programming was to keep track of which functions called which other functions, and what data was changed. To make sense of this potentially confusing situation, structured programming was created. The principal idea behind structured programming is the concept of divide and conquer.A computer program can be thought of as consisting of a set of tasks. Any task that is too complex to be described simply is broken down into a set of smaller component tasks until the tasks are sufficiently small and self-contained enough that each is easily understood.

What is Object-Oriented Programming?


Object-oriented programming has taken the best ideas of structured programming and has combined them with several powerful concepts that allow us to organize our programs more effectively. Object-oriented programming responds to these programming requirements, providing techniques for managing enormous complexity, achieving reuse of software components, and coupling data with the tasks that manipulate that data. The essence of object-oriented programming is to model objects (that is, things or concepts) rather than data. The objects we model might be onscreen widgets, such as buttons and list boxes, or they might be realworld objects, such as customers, bicycles, airplanes, cats, and water. Objects have characteristics, also called properties or attributes, such as age, fast, spacious, black, or wet. They also have capabilities, also called operations or functions, such as purchase, accelerate, fly, purr, or bubble. It is the job of object-oriented programming to represent these objects in the programming language.

C++ and Object-Oriented Programming


C++ fully supports object-oriented programming, including the three pillars of object oriented development: encapsulation, inheritance, and polymorphism.

Encapsulation The property of being a self-contained unit is called encapsulation. With encapsulation, we can accomplish data hiding. Data hiding is the highly valued characteristic that an object can be used without the user knowing or caring how it works internally. Similarly, when the engineer uses the resistor, she need not know anything about the internal state of the resistor. All the properties of the resistor are encapsulated in the resistor object; they are not spread out through the circuitry. It is not necessary to

understand how the resistor works to use it effectively. Its workings are hidden inside the resistors casing.

Inheritance and Reuse


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. A derived class represents a more specialized group of objects. Typically, a derived class contains behaviors inherited from its base class plus additional behaviors. A direct base class is the base class from which a derived class explicitly inherits. An indirect base class is inherited from two or more levels up in the class hierarchy. In the case of single inheritance, a class is derived from one base class. C++ also supports multiple inheritance, in which a derived class inherits from multiple (possibly unrelated) base classes. C++ offers three kinds of inheritance public, protected and private.

Polymorphism
Polymorphism enables us to "program in the general" rather than "program in the specific." In particular, polymorphism enables us to write programs that process objects of classes that are part of the same class hierarchy as if they are all objects of the hierarchy's base class. With polymorphism, we can design and implement systems that are easily extensiblenew classes can be added with little or no modification to the general portions of the program, as long as the new classes are part of the inheritance hierarchy that the program processes generically. The only parts of a program that must be altered to accommodate new classes are those that require direct knowledge of the new classes that the programmer adds to the hierarchy. For example, if we create class Tortoise that inherits from class Animal, we need to write only the Tortoise class and the part of the simulation that instantiates a Tortoise object. The portions of the simulation that process each Animal generically can remain the same.

Programs on Classes
1. #include <iostream> class Cat // declare the Cat class { public: // members that follow are public int itsAge; // member variable int itsWeight; // member variable } int main() { Cat Frisky; Frisky.itsAge = 5; // assign to the member variable std::cout << Frisky is a cat who is ; std::cout << Frisky.itsAge << years old.\n;
return 0; }

2.
// Demonstrates declaration of a class and // definition of class methods #include <iostream> // for cout class Cat // begin declaration of the class { public: // begin public section int GetAge(); // accessor function void SetAge (int age); // accessor function void Meow(); // general function private: // begin private section int itsAge; // member variable }; // GetAge, Public accessor function // returns value of itsAge member int Cat::GetAge() { return itsAge; } // definition of SetAge, public

// accessor function // sets itsAge member void Cat::SetAge(int age) // set member variable itsAge to { // value passed in by parameter age itsAge = age; }

// definition of Meow method // returns: void // parameters: None // action: Prints meow to screen void Cat::Meow() { std::cout << Meow.\n; } // create a cat, set its age, have it // meow, tell us its age, then meow again. int main() { Cat Frisky; Frisky.SetAge(5); Frisky.Meow(); std::cout << Frisky is a cat who is ; std::cout << Frisky.GetAge() << years old.\n; Frisky.Meow(); return 0; }

Constructors and Destructors


We can initialize the member data of a class using a special member function called a constructor. The constructor can take parameters as needed, but it cannot have a return valuenot even void. The constructor is a class method with the same name as the class itself. Whenever we declare a constructor, well also want to declare a destructor. Just as constructors create and initialize objects of your class, destructors clean up after your object and free any resources or memory that we might have allocated (either in the constructor or throughout the lifespan of the object). A destructor always has the name of the class, preceded by a tilde (~). Destructors take no arguments and have no return value. 3. Using Constructors and Destructors
// Demonstrates declaration of constructors and // destructor for the Cat class // Programmer created default constructor #include <iostream> // for cout class Cat // begin declaration of the class { public: // begin public section Cat(int initialAge); // constructor ~Cat(); // destructor int GetAge(); // accessor function void SetAge(int age); // accessor function void Meow(); private: // begin private section int itsAge; // member variable }; // constructor of Cat Cat::Cat(int initialAge) { itsAge = initialAge; }

Cat::~Cat() // destructor, takes no action { } // GetAge, Public accessor function // returns value of itsAge member int Cat::GetAge() { return itsAge; }: // Definition of SetAge, public // accessor function void Cat::SetAge(int age) { // set member variable itsAge to // value passed in by parameter age itsAge = age; } // definition of Meow method // returns: void // parameters: None // action: Prints "meow" to screen void Cat::Meow() { std::cout << "Meow.\n"; } // create a cat, set its age, have it // meow, tell us its age, then meow again. int main() { Cat Frisky(5); Frisky.Meow(); std::cout << "Frisky is a cat who is " ; std::cout << Frisky.GetAge() << " years old.\n"; Frisky.Meow(); Frisky.SetAge(7); std::cout << "Now Frisky is " ; std::cout << Frisky.GetAge() << " years old.\n"; return 0; }

Inheritance and Reuse


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. A derived class represents a more specialized group of objects. Typically, a derived class contains behaviors inherited from its base class plus additional behaviors. A direct base class is the base class from which a derived class explicitly inherits. An indirect base class is inherited from two or more levels up in the class hierarchy. In the case of single inheritance, a class is derived from one base class. C++ also supports multiple inheritance, in which a derived class inherits from multiple (possibly unrelated) base classes. C++ offers three kinds of inheritance public, protected and private. A class can be derived from an existing class by using the form class class-name : (public|protected|private)optbase-name { member declarations };

4.
//This program illustrates how constructors and destructors //execute in a base class.

#include <iostream> using namespace std; class Test_Class { protected: int n; public: Test_Class(int i = 0); //One-argument constructor ~Test_Class(); }; Test_Class::Test_Class(int i) : n(i) { cout << endl; cout << "Test_Class Constructor Executed: Data member initialized to " << n << endl; } Test_Class::~Test_Class() { cout << endl; cout << "Test_Class Destructor Executed for object with data member " << n << endl; } class Derived_Test_Class : public Test_Class { protected: int m; public: Derived_Test_Class(int j = 0); ~Derived_Test_Class(); }; Derived_Test_Class::Derived_Test_Class(int j) : Test_Class(j+1), m(j) { cout << endl; cout << "Derived_Test_Class Constructor Executed: " << "Data member initialized to " << m <<endl; } Derived_Test_Class::~Derived_Test_Class() { cout << endl; cout << "Derived_Test_Class Destructor Executed " << "for object with data member " << m << endl; }

int main() { cout << "Test_Class object being created:" << endl; Test_Class tc_object1(4); cout << endl; cout << "Derived_Test_Class object being created:" << endl; Derived_Test_Class dtc_object1(7); return 0; }

5. // Virtual function selection


class Base { public: virtual void print() const { cout << " inside Base" << endl; } }; class Derived : public Base { public: // virtual as well void print() const { cout << " inside Derived" << endl; } }; int main() { Base b; Derived f; Base* pb = &b; // points at a Base object pb -> print(); // call Base::print() pb = &f; // points at Derived object pb -> print(); // call Derived::print() }

The output of this program is Inside base Inside drived

You might also like