HISTORY OF C++
Bjarne Stroustrup began work on "C with Classes" in 1979.The idea of creating a new language originated from Stroustrup's experience in programming for his Ph.D. thesis. Stroustrup found that Simula
had features that were very helpful for large software development, but the language was too slow for practical use, while BCPL
was fast but too low-level to be suitable for large software development. When Stroustrup started working in AT&T Bell Labs
, he had the problem of analyzing the UNIX
kernel with respect todistributed computing
. Remembering his Ph.D. experience, Stroustrup set out to enhance the C language with Simula
-like features. C was chosen because it was general-purpose, fast, portable and widely used. Besides C and Simula, some other languages that inspired him were ALGOL 68
, Ada
, CLU
and ML
. At first, the class, derived class, strong type checking, inlining
, and default argument features were added to C via Stroustrup's C++ to C compiler, Cfront
. The first commercial implementation of C++ was released on 14 October 1985.
In 1983, the name of the language was changed from
C with Classes to C++ (++ being the increment operator in C). New features were added including virtual functions, function name and operator overloading, references, constants, user-controlled free-store memory control, improved type checking, and BCPL style single-line comments with two forward slashes (
//
). In 1985, the first edition of
The C++ Programming Language was released, providing an important reference to the language, since there was not yet an official standard.Release 2.0 of C++ came in 1989 and the updated second edition of
The C++ Programming Language was released in 1991. New features included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990,
The Annotated C++ Reference Manual was published. This work became the basis for the future standard. Late feature additions included templates,exceptions, namespaces, new
casts, and a Boolean type.
As the C++ language evolved, the standard library evolved with it. The first addition to the C++ standard library was the stream I/O library which provided facilities to replace the traditional C functions such as printf and
scanf. Later, among the most significant additions to the standard library, was large amounts of the Standard Template Library.
C++ is sometimes called a hybrid language.
It is possible to write object oriented or procedural code in the same program in C++. This has caused some concern that some C++ programmers are still writing procedural code, but are under the impression that it is object oriented, simply because they are using C++. Often it is an amalgamation of the two. This usually causes most problems when the code is revisited or the task is taken over by another coder.
C++ continues to be used and is one of the preferred programming languages to develop professional applications
Objects
Main article: C++ classes
C++ introduces object-oriented programming (OOP)
Oops concepts and c++ overview by J.SURIYA
features to C. It offers classes, which provide the four features commonly present in OOP (and some non-OOP) languages:abstraction, encapsulation, inheritance, and
polymorphism. Objects are instances of classes created at runtime. One distinguishing feature of C++ classes compared to classes in other programming languages is support for deterministic
destructors, which in turn provide support for the
Resource Acquisition is Initialization concept.
CLASS
Aggregate classes
An aggregate class is a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.
[2] Such a class can be initialized with a brace-enclosed comma-separated list of initializer-clauses.
[3] The following code has the same semantics in both C and C++.
struct C
{
int a;
double b;
};
struct D
{
int a;
double b;
C c;
};
// initialize an object of type C with an initializer-list
C c = {1, 2};
// D has a sub-aggregate of type C. In such cases initializer-clauses can be nested
D d = {10, 20, {1, 2}};
Basic declaration and member variables
Classes are declared with the
class
or
struct
keyword. Declaration of members are placed within this declaration.
struct person
{
string name;
int age;
};
|
class person
{
public:
string name;
int age;
};
|
The above definitions are functionally equivalent. Either code will define objects of type
person
as having two public data members,
name
and
age
. The
semicolons after the closing braces are mandatory.
After one of these declarations (but not both), person
can be used as follows to create newly defined variables of the person
datatype:
#include <iostream>
#include <string>
using namespace std;
class person
{
public:
string name;
int age;
};
int main()
{
person a, b;
a.name = "Calvin";
b.name = "Hobbes";
a.age = 30;
b.age = 20;
cout << a.name << ": " << a.age << endl;
cout << b.name << ": " << b.age << endl;
return 0;
}
Executing the above code will output
Calvin: 30
Hobbes: 20
Member functions
An important feature of the C++ class and structure are
member functions. Each datatype can have its own built-in functions (referred to as methods) that have access to all (public and private) members of the datatype. In the body of these non-static member functions, the keyword
this
can be used to refer to the object for which the function is called. This is commonly implemented by passing the address of the object as an implicit first argument to the function.
[10] Take the above
person
type as an example again:
class person
{
std::string name;
int age;
public:
person() : age(5) { }
void print() const;
};
void person::print() const
{
cout << name << ":" << age << endl;
/* "name" and "age" are the member variables.
The "this" keyword is an expression whose value is the address
of the object for which the member was invoked. Its type is
const person*, because the function is declared const.
*/
}
Encapsulation
Encapsulation is the method of combining the data and functions inside a class. This hides the data from being accessed from outside a class directly, only through the functions inside the class is able to access the information.
This is also known as "Data Abstraction", as it gives a clear separation between properties of data type and the associated implementation details. There are two types, they are "function abstraction" and "data abstraction". Functions that can be used without knowing how its implemented is function abstraction. Data abstraction is using data without knowing how the data is stored.
Encapsulation is the hiding of information in order to ensure that data structures and operators are used as intended and to make the usage model more obvious to the developer. C++ provides the ability to define classes and functions as its primary encapsulation mechanisms. Within a class, members can be declared as either public, protected, or private in order to explicitly enforce encapsulation. A public member of the class is accessible to any function. A private member is accessible only to functions that are members of that class and to functions and classes explicitly granted access permission by the class ("friends"). A protected member is accessible to members of classes that inherit from the class in addition to the class itself and any friends.
The OO principle is that all of the functions (and only the functions) that access the internal representation of a type should be encapsulated within the type definition. C++ supports this (via member functions and friend functions), but does not enforce it: the programmer can declare parts or all of the representation of a type to be public, and is allowed to make public entities that are not part of the representation of the type. Therefore, C++ supports not just OO programming, but other weaker decomposition paradigms, like modular programming.
It is generally considered good practice to make all
data private or protected, and to make public only those functions that are part of a minimal interface for users of the class. This can hide the details of data implementation, allowing the designer to later fundamentally change the implementation without changing the interface in any way
Example:
#include <iostream.h>
class Add
{
private:
int x,y,r;
public:
int Addition(int x, int y)
{
r= x+y;
return r;
}
void show( )
{ cout << "The sum is::" << r << "\n";}
}s;
void main()
{
Add s;
s.Addition(10, 4);
s.show();
}
|
Result:
The sum is:: 14
In the above encapsulation example the integer values "x,y,r" of the class "Add" can be accessed only through the function "Addition". These integer values are encapsulated inside the class "Add"
POINTERS
Pointers refer the memory location of a variable using a reference operator. The reference operator is the "&" symbol, which means the "address of".
Pointers can be used to directly access the value stored in the variable using the "*" operator known as a "dereference operator".Another dereference operator is "->", which dereferences to a structure or union.
Example:
#include <iostream.h>
int main ()
{
int value;
int * ptr;
ptr = &value;
*ptr = 12;
cout << "The value is:: " << value << endl;
return 0;
}
|
Result:
The value is:: 12
In the above example an integer "value" and a pointer "ptr" is declared first. The address of the variable "value" is pointed by the "ptr". Now the values of the "ptr" is assigned to 12.
INHERITANCE
Inheritance allows one data type to acquire properties of other data types.
Inheritance, polymorphisam, abstract classes and composition) from J.SURIYA
Inheritance from a base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately, while a "struct" inherits publicly. Base classes may be declared as virtual; this is called virtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.
Multiple inheritance is a C++ feature not found in most other languages, allowing a class to be derived from more than one base classes; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such as C# or Java, accomplish something similar (although more limited) by allowing inheritance of multiple
interfaces while restricting the number of base classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or member data). An interface as in C# and Java can be defined in C++ as a class containing only pure virtual functions, often known as an
abstract base class or "ABC". The member functions of such an abstract base class are normally explicitly defined in the derived class, not inherited implicitly. C++ virtual inheritance exhibits an ambiguity resolution feature called
dominance.
POLYMORPHISM
Polymorphism
In object-oriented programming, polymorphism (from the Greek meaning "having
multiple forms") is the characteristic of being able to assign a different meaning to a
particular symbol or "operator" in different contexts.
The simple example is two classes that inherit from a common parent and implement the
same virtual method.
class A
{
public:
virtual void f()=0;
};
class B
{
public:
virtual void f()
{std::cout << "Hello from B" << std::endl;};
};
class C
{
public:
virtual void f()
{std::cout << "Hello from C" << std::endl;};
};
If I have an object A, then calling the method f() will produce different results depending
on the context, the real type of the object A.
func(A & a)
{
A.f();
};
Polymorphism enables one common interface for many implementations, and for objects to act differently under different circumstances.
C++ supports several kinds of static (compile-time) and dynamic (run-time) polymorphisms. Compile-time polymorphism does not allow for certain run-time decisions, while run-time polymorphism typically incurs a performance penalty.
Static polymorphism
Function overloading allows programs to declare multiple functions having the same name (but with different arguments). The functions are distinguished by the number or types of their formal parameters. Thus, the same function name can refer to different functions depending on the context in which it is used. The type returned by the function is not used to distinguish overloaded functions and would result in a compile-time error message.
When declaring a function, a programmer can specify for one or more parameters a default value. Doing so allows the parameters with defaults to optionally be omitted when the function is called, in which case the default arguments will be used. When a function is called with fewer arguments than there are declared parameters, explicit arguments are matched to parameters in left-to-right order, with any unmatched parameters at the end of the parameter list being assigned their default arguments. In many cases, specifying default arguments in a single function declaration is preferable to providing overloaded function definitions with different numbers of parameters.
Templates in C++ provide a sophisticated mechanism for writing generic, polymorphic code. In particular, through the Curiously Recurring Template Pattern, it's possible to implement a form of static polymorphism that closely mimics the syntax for overriding virtual functions. Since C++ templates are type-aware and Turing-complete, they can also be used to let the compiler resolve recursive conditionals and generate substantial programs through template metaprogramming. Contrary to some opinion, template code will not generate a bulk code after compilation with the proper compiler settings
Virtual member functions
Ordinarily, when a function in a derived class overrides a function in a base class, the function to call is determined by the type of the object. A given function is overridden when there exists no difference in the number or type of parameters between two or more definitions of that function. Hence, at compile time, it may not be possible to determine the type of the object and therefore the correct function to call, given only a base class pointer; the decision is therefore put off until runtime. This is called dynamic dispatch. Virtual member functions or methods allow the most specific implementation of the function to be called, according to the actual run-time type of the object. In C++ implementations, this is commonly done using virtual function tables. If the object type is known, this may be bypassed by prepending a fully qualified class name before the function call, but in general calls to virtual functions are resolved at run time.
In addition to standard member functions, operator overloads and destructors can be virtual. A general rule of thumb is that if any functions in the class are virtual, the destructor should be as well. As the type of an object at its creation is known at compile time, constructors, and by extension copy constructors, cannot be virtual. Nonetheless a situation may arise where a copy of an object needs to be created when a pointer to a derived object is passed as a pointer to a base object. In such a case, a common solution is to create a clone()
(or similar) virtual function that creates and returns a copy of the derived class when called.
A member function can also be made "pure virtual" by appending it with = 0
after the closing parenthesis and before the semicolon. A class containing a pure virtual function is called an abstract data type. Objects cannot be created from abstract data types; they can only be derived from. Any derived class inherits the virtual function as pure and must provide a non-pure definition of it (and all other pure virtual functions) before objects of the derived class can be created. A program that attempts to create an object of a class with a pure virtual member function or inherited pure virtual member function is ill-formed.
#include <iostream>
#include <memory>
#include <vector>
class Animal {
public:
virtual void eat() {
std::cout << "I eat like a generic animal.\n";
}
// polymorphic deletes require a virtual base destructor
virtual ~Animal() {
}
};
class Wolf : public Animal {
public:
void eat() {
std::cout << "I eat like a wolf!\n";
}
};
class Fish : public Animal {
public:
void eat() {
std::cout << "I eat like a fish!\n";
}
};
class GoldFish : public Fish {
public:
void eat() {
std::cout << "I eat like a goldfish!\n";
}
};
class OtherAnimal : public Animal {
};
int main() {
std::vector<std::unique_ptr<Animal> > animals;
animals.push_back(std::unique_ptr<Animal>(new Animal));
animals.push_back(std::unique_ptr<Animal>(new Wolf));
animals.push_back(std::unique_ptr<Animal>(new Fish));
animals.push_back(std::unique_ptr<Animal>(new GoldFish));
animals.push_back(std::unique_ptr<Animal>(new OtherAnimal));
for (auto it = animals.begin(); it != animals.end(); ++it) {
(*it)->eat();
}
}
Output with the virtual function Animal::eat():
I eat like a generic animal.
I eat like a wolf!
I eat like a fish!
I eat like a goldfish!
I eat like a generic animal.
Output if Animal::eat() were not declared as virtual:
I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.
I eat like a generic animal.
STRUCTURES
Structures in C++ is a collection of variables. Structures in C++ can be declared even without the keyword "struct". By default all the members of a structure are "public", even "private" members can also be declared in a function.
Syntax:
struct struct-type-name{
type name1: length;
type name2: length;
.
.
type nameN : length;
}variable_list;
Example:
#include <iostream.h>
struct Emp
{
int empno;
int empsal;
};
void main( )
{
Emp emp1= { 23, 12000};
cout << "Employee Number::" <<
emp1.empno << '\n';
cout << "Employee Salary:: "<< emp1.empsal;
}
|
Result:
Employee Number:: 23
Employee Salary:: 12000
In the above example, the structure "Emp" is used initialize the integers, that are referenced in the "main()" function.
Unions:
Unions in C++ is a user defined data type that uses the same memory as other objects from a list of objects. At an instance it contains only a single object.
Syntax:
union union-type-name{
type member-name;
type member-name;
}union-variables;
Example:
#include <iostream.h>
union Emp
{
int num;
double sal;
};
int main()
{
Emp value;
value.num = 2;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
value.sal = 2000.0;
cout << "Employee Number::" << value.num
<< "\nSalary is:: " << value.sal << endl;
return 0;
}
|
Result:
Employee number is::2
Salary is::2.122e-314
Employee number is::0
Salary is::2000
In the above example, only "value.num" is assigned, but still the "val.sal" gets a value automatically, since the memory locations are same.