Sei sulla pagina 1di 11

C Sharp Tutorial

C# Tutorials
Objects:

This is the basic unit of object oriented programming. That is both data and function that
operate on data are bundled as a unit called as object.

Classes:

The concept of class is similar to the concept of structure in C. In other words classes are
the data types on which objects are created. So while a class is created no memory is
allocated only when an object is created memory gets allocated.

Inheritance:

As the name suggests Inheritance is the process of forming a new class from an existing
class that is from the existing class called as base class, new class is formed called as
derived class. This is a very important concept of object oriented programming since this
feature helps to reduce the code size.

Data Abstraction:

By this feature of object oriented programming it is possible to represent the needed


information in program without presenting the details. Also by the feature of data
abstraction it is possible to create user defined data types and thus increase the power of
programming language.

Data Encapsulation:

Data Encapsulation is the process of combining data and functions into a single unit
called class. By this method one cannot access the data directly. Data is accessible only
through the functions present inside the class. Thus Data Encapsulation gave rise to the
important concept of data hiding.

Polymorphism:

The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers
many. That is a single function or an operator functioning in many ways different upon
the usage is called polymorphism.

What is an Object?
An object is a software bundle of related state and behavior.
Software objects are often used to model the real-world objects that you find in everyday
life. Real-world objects share two characteristics: They all have state and behavior.

Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging
tail).
SUNSAT The Perfect Team
C Sharp Tutorial
Software objects are conceptually similar to real-world objects:
they too consist of state and related behavior.
An object stores its state in fields (variables in some programming languages)
and exposes its behavior through methods (functions in some programming languages).

Methods operate on an object’s internal state and serve as the primary mechanism for
object-to-object communication.

Hiding internal state and requiring all interaction to be performed through an object’s
methods is known as
data encapsulation — a fundamental principle of object-oriented programming

What Is a Class?
A class is a blueprint or prototype from which objects are created.

What Is Inheritance?
Inheritance provides a powerful and natural mechanism for organizing and structuring
your software.

What Is an Interface?
An interface is a contract between a class and the outside world.
When a class implements an interface, it promises to provide the behavior published by
that interface.

What Is a Package?
A package is a namespace for organizing classes and interfaces in a logical manner.
Placing your code into packages makes large software projects easier to manage.

Overloading:

The concept of overloading is also a branch of polymorphism. When the exiting operator
or function is made to operate on new data type it is said to be overloaded.

Reusability:

That is object oriented programming has the feature of allowing an existing class which is
written and debugged to be used by other programmers and there by provides a great time
saving and also code efficiency to the language. Also it is possible to a have the existing
class and adds new features to the existing class as pet the programmer’s choice.

Thus the object oriented programming features helps the program ad there by users of the
application to achieve increased performance, it saves time of developing the application,
give optimized code for the application, helps in gaining secured applications and there
by helps in easier maintenance.

We will learn how to implement each of these feature of object oriented programming in
C++ later in later sections.
SUNSAT The Perfect Team
C Sharp Tutorial
Basic Structure:

To start with the programming language C++ let us see how a have an overlook of basic
structure of C++ program.

Let us see a sample program to have an understanding of the basic structure of C++

//program to read employee details and to output the data Comment


#include < iostream.h > Preprocessor Statement
class employee Class Declaration
{
private:
char empname[50];
int empno;
public:
void getvalue()
{
cout< < ”INPUT EMP NAME:”;
cint > >empname;
cout< < ”INPUT EMP NO:”;
cint > >empno;
}
void displayvalue()
{
cout< < ”EMP NAME:”< < empname;
coout< < EMP NO:”< < empno;
}
};
main()
{
employee e1; Creation of Object
e1.getvalue();
e1.displayvalu();
}

Though the later section would explain each section in detail let us see overlook of the
structure of the above program.

Class:

A class in C++ is an encapsulation of data members and functions that manipulate the
data. The class can also have some other important members which are architecturally
important.

This C++ Tutorial discusses the components of a C++ class. More C++ tutorials will
follow.

C++ Tutorial - Class Data Members:

SUNSAT The Perfect Team


C Sharp Tutorial
Very important point about the Data members in this C++ Tutorial! This title is not a
keyword or a data type in C++. This is just to explain one of the logical classifications of
the types of members that are available in C++.

The data members can be of any legal data type, a class type, a struct type etc., They can
also be declared as pointers and accessible normally as like other data members. The
Example class given below in this C++ tutorial has two data members x and y of type
integer.

C++ Tutorial - Function members in classes:

Functions declared inside a class can be any of the following four types. This C++
Tutorial explains each one of them as below.

Ordinary member functions:

These are ordinary functions defined with a return type and parameters. The return type
can also be void. The special trait about member functions is they can access the
private/protected data members of their class and manipulate them. No external functions
can access the private/protected data members of a class. The sample below this C++
Tutorial uses an ordinary member function Add(), returning an integer value.

Constructors:

Constructors in C++ are special member functions of a class. They have the same name
as the Class Name. There can be any number of overloaded constructors inside a class,
provided they have a different set of parameters. There are some important qualities for a
constructor to be noted.

• Constructors have the same name as the class.


• Constructors do not return any values
• Constructors are invoked first when a class is initialized. Any initializations for
the class members, memory allocations are done at the constructor.

In the example class given below in this C++ tutorial has the constructor
Example_Class(), with the same name as the class.

Destructors:

Destructors in C++ also have the same name, except for the fact that they are preceded
by a ‘~’ operator. The destructors are called when the object of a class goes out of scope.
It is not necessary to declare a constructor or a destructor inside a class. If not declared,
the compiler will automatically create a default one for each. If the constructor/destructor
is declared as private, then the class cannot be instantiated. Check below for the sample
class of the C++ tutorial for an example of destructor.

C++ Tutorial - Access Level:

SUNSAT The Perfect Team


C Sharp Tutorial
The classes in C++ have 3 important access levels. They are Private, Public and
Protected. The explanations are as follows.

Private:

The members are accessible only by the member functions or friend functions.

Protected:

These members are accessible by the member functions of the class and the classes
which are derived from this class.

Public:

Accessible by any external member. Look at the sample class below.

C++ Tutorial - Example of a class:

class Example_class //Sample Class for the C++ Tutorial


{
private:
int x; //Data member
int y; // Data member
public:
Example_Class() //Constructor for the C++ tutorial
{
x = 0;
y = 0;
}
~Example_Class() //destructor for the C++ Tutorial
{}
int Add()
{
return x+y;
}
};

Inheritence
Creating or deriving a new class using another class as a base is called inheritance in
C++. The new class created is called a Derived class and the old class used as a base is
called a Base class in C++ inheritance terminology.

The derived class will inherit all the features of the base class in C++ inheritance. The
derived class can also add its own features, data etc., It can also override some of the
features (functions) of the base class, if the function is declared as virtual in base class.

SUNSAT The Perfect Team


C Sharp Tutorial
C++ inheritance is very similar to a parent-child relationship. When a class is inherited
all the functions and data member are inherited, although not all of them will be
accessible by the member functions of the derived class. But there are some exceptions to
it too.

Some of the exceptions to be noted in C++ inheritance are as follows.

• The constructor and destructor of a base class are not inherited


• The assignment operator is not inherited
• The friend functions and friend classes of the base class are also not inherited.

There are some points to be remembered about C++ inheritance. The protected and
public variables or members of the base class are all accessible in the derived class. But a
private member variable not accessible by a derived class.

It is a well known fact that the private and protected members are not accessible outside
the class. But a derived class is given access to protected members of the base class.

Let us see a piece of sample code for C++ inheritance. The sample code considers a class
named vehicle with two properties to it, namely color and the number of wheels. A
vehicle is a generic term and it can later be extended to any moving vehicles like car,
bike, bus etc.,

class vehicle //Sample base class for c++ inheritance tutorial


{
protected:
char colorname[20];
int number_of_wheels;
public:
vehicle();
~vehicle();
void start();
void stop();
void run();
};

class Car: public vehicle //Sample derived class for C++ inheritance tutorial
{
protected:
char type_of_fuel;
public:
Car();
};

The derived class Car will have access to the protected members of the base class. It can
also use the functions start, stop and run provided the functionalities remain the same.

In case the derived class needs some different functionalities for the same functions start,
stop and run, then the base class should implement the concept of virtual functions.

SUNSAT The Perfect Team


C Sharp Tutorial
Pointers
We can define a variable in C++ to store a memory address. A pointer in C++ is said to
"point to" the memory address that is stored in it. Also, when defining a C++ pointer
variable, we must specify the type of variable to which it is pointing. For example, to
define a pointer, which will store a memory address at which exists an int, we can do the
following:

//Sample program for c++ pointer


signed main()
{
int* p;
//Right now, p contains no particular myval in this C++ code.
}

The asterisk in the above specifies that we have a pointer variable. Let’s say we want to
define an int variable and then we want to define a pointer variable, which will store the
memory address of this int:

//c++ pointer using an int variable

signed main()
{
int myval(7);
int* p_myval;
//Right now, p_myval contains no particular myval.
p_myval = &myval;
//Now, p_myval in this c++ program contains the memory address of the variable myval
}

With &myval, & is referred to as "the address-of operator". The expression &myval is of
the c++ type int*. We then store this int* myval in our int* variable, which is p_myval.
Now, we will actually use this pointer:

//Sample program for c++ pointer

signed main()
{
int myval = 7;
int* p_myval = &myval;
*p_myval = 6;
}

With *p_myval = 6, the asterisk is referred to as "the dereference operator". It turns the
expression from an int* into an int. The statement has the effect of setting the myval of
myval to 6. So now what are the uses of pointers in c++? Let us see something about how
and when they should be used:

A) When the pointer must be re-seated.


SUNSAT The Perfect Team
C Sharp Tutorial
B) When arrays are involved.

Consider a string, an array of characters:

signed int main()


{
char my_name[] = "Code";
}

Here’s what the string (char c++ pointer) looks like in memory:

Name of Variable Type of Variable Address in Memory Value Stored


my_name Char 108 ‘C’
char 109 ‘o’
char 110 ‘d’
char 111 ‘e’
char 112 ‘\0’
While accessing the characters inside the variable my_name, the position of the first
character will start from 0. So the array of size 4 will be accessed for characters from 0,
1, 2 and 3. We can define a pointer to point to the second element in the array my_name,
as so:

int main()
{
char my_name[] = "Code";
char* k( &my_name[1] );
}

Now, what k points to looks like so in memory:

Name of Variable Type of Variable Address in Memory Value Stored


my_name Char* 116 109
char 109 ‘o’
char 110 ‘d’
char 111 ‘e’
char 112 ‘\0’
So that’s one usage of c++ pointers there, to point to an individual object in an array.
The other feature of c++ pointers is that they can be "re-seated", which means that you
can change their value, you can change what they’re pointing to, as in the following: //
c++ pointer program for modifying values/re-seating.

signed int main()


{
int myval(5);
int myvalue2 = 7;
int* p_primate;
SUNSAT The Perfect Team
C Sharp Tutorial
p_primate = &myval;
*p_primate = 9;
p_primate = &myvalue2;
*p_primate = 10;
}

Guess what kind of variable we have in the following:

signed main()
{
signed** p_p_cow;
}

An int* c++ pointer points to an int, so an int** points to an int*. In English: The
variable p_cow above stores a memory address. At that memory address exists a variable
of type int*. This int* variable also stores a memory address, at which exists an int. Take
the following:

//Snippet for c++ pointer to pointers

int main()
{
int cow(7);
int* p_cow = &cow;
int** p_p_cow(&p_cow);
int*** p_p_p_cow = &p_p_cow;
}

Here’s what the above c++ pointers look like in memory:

Name of Variable Type of Variable Address in Memory Value Stored


Cow Int 108 7
p_cow int* 110 108
p_p_cow int** 112 110
p_p_p_cow int*** 114 112
With the above code, we can set the value of cow using p_p_p_cow:

//Using c++ pointer to pointer

int main()
{
int cow(7);
int* p_cow = &cow;
int** p_p_cow(&p_cow);
int*** p_p_p_cow = &p_p_cow;
***p_p_p_cow = 8;
}

SUNSAT The Perfect Team


C Sharp Tutorial
C++ Pointers are commonly used when working with strings. Let’s define a function;
this function will be supplied with a string. We’re going to change the 2nd, 5th and 7th
characters of the string:

void ChangeString(char* const p_first_char)


{
p_first_char[1] = ‘a’;
p_first_char[4] = ‘b’;
p_first_char[6] = ‘c’;
}

Or we can define a function, which will be supplied with a string. The function will
return the first instance of the character ‘t’ in the string:

char* GetFirstT(char* p_first_char)


{

for ( ; *p ; ++p)
{
if ( *p == ‘t’ ) return p;
}
return 0;

signed main()
{

char the_alphabet[] = "abcdefghijklmnopqrstuvwxyz";


char* p_t = GetFirstT(the_alphabet);

Now I’m going to talk about c++ pointers and constness. If you want a const c++ pointer
variable, a c++ pointer variable whose value you can’t change after initialization, then
stick the const directly beside the variable’s name:

signed main()
{

int myval = 5;
int myvalue2(8);
int* const p_k = &myval;
p_k = &myvalue2; //COMPILE ERROR
*p_k = 3; //No problem, the variable to which it points is non-const

SUNSAT The Perfect Team


C Sharp Tutorial
If you want a non-const c++ pointer variable, but you want the variable to which it
points to be const, then:

signed main()
{

int myval(7);
int myvalue2 = 6;
const int* p_k = &myval;
p_k = &myvalue2; //No problem, the variable is non-const
*p_k = 7; //COMPILE ERROR

If you want a const c++ pointer that points to a const variable then:

signed int main()


{

int myval(17);
int myvalue2 = 4;
const int* const p_k = &myval;
p_k = &myvalue2; //COMPILE ERROR
*p_k = 32; //COMPILE ERROR

SUNSAT The Perfect Team

Potrebbero piacerti anche