You are on page 1of 12

C Sharp Tutorial

C# Tutorials
Objects: This is the basic unit of object oriented programming. That is both dat
a and function that operate on data are bundled as a unit called as object. Clas
ses: 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 all
ocated. 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 bas
e class, new class is formed called as derived class. This is a very important c
oncept of object oriented programming since this feature helps to reduce the cod
e size. Data Abstraction: By this feature of object oriented programming it is p
ossible to represent the needed information in program without presenting the de
tails. Also by the feature of data abstraction it is possible to create user def
ined data types and thus increase the power of programming language. Data Encaps
ulation: 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 Dat
a 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 giv
ing different meaning or functions to the operators or functions is called polym
orphism. 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. R
eal-world objects share two characteristics: They all have state and behavior. D
ogs have state (name, color, breed, hungry) and behavior (barking, fetching, wag
ging 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 throug
h methods (functions in some programming languages). Methods operate on an objec
t’s internal state and serve as the primary mechanism for object-to-object commu
nication. Hiding internal state and requiring all interaction to be performed th
rough an object’s methods is known as data encapsulation — a fundamental princip
le of object-oriented programming What Is a Class? A class is a blueprint or pro
totype 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 behavio
r published by that interface. What Is a Package? A package is a namespace for o
rganizing classes and interfaces in a logical manner. Placing your code into pac
kages makes large software projects easier to manage. Overloading: The concept o
f overloading is also a branch of polymorphism. When the exiting operator or fun
ction is made to operate on new data type it is said to be overloaded. Reusabili
ty: 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 c
lass as pet the programmer’s choice. Thus the object oriented programming featur
es helps the program ad there by users of the application to achieve increased p
erformance, it saves time of developing the application, give optimized code for
the application, helps in gaining secured applications and there by helps in ea
sier 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 s
ample program to have an understanding of the basic structure of C++ //program t
o read employee details and to output the data Comment #include < iostream.h > P
reprocessor Statement class employee Class Declaration { private: char empname[5
0]; int empno; public: void getvalue() { cout< < ”INPUT EMP NAME:”; cint > >empn
ame; cout< < ”INPUT EMP NO:”; cint > >empno; } void displayvalue() { cout< < ”EM
P NAME:”< < empname; coout< < EMP NO:”< < empno; } }; main() { employee e1; Crea
tion 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 abov
e program. Class: A class in C++ is an encapsulation of data members and functio
ns that manipulate the data. The class can also have some other important member
s which are architecturally important. This C++ Tutorial discusses the component
s of a C++ class. More C++ tutorials will follow. C++ Tutorial - Class Data Memb
ers: SUNSAT The Perfect Team
C Sharp Tutorial Very important point about the Data members in this C++ Tutoria
l! This title is not a keyword or a data type in C++. This is just to explain on
e 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 othe
r 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: Fun
ctions 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 ar
e 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 th
e 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 int
eger 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 ove
rloaded constructors inside a class, provided they have a different set of param
eters. There are some important qualities for a constructor to be noted.
• • •
Constructors have the same name as the class. Constructors do not return any val
ues Constructors are invoked first when a class is initialized. Any initializati
ons for the class members, memory allocations are done at the constructor.
In the example class given below in this C++ tutorial has the constructor Exampl
e_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 ‘~’ operato
r. The destructors are called when the object of a class goes out of scope. It i
s 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 instanti
ated. Check below for the sample class of the C++ tutorial for an example of des
tructor. C++ Tutorial - Access Level:
SUNSAT The Perfect Team
C Sharp Tutorial The classes in C++ have 3 important access levels. They are Pri
vate, Public and Protected. The explanations are as follows. Private: The member
s are accessible only by the member functions or friend functions. Protected: Th
ese 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. Lo
ok at the sample class below. C++ Tutorial - Example of a class: class Example_c
lass //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() { re
turn x+y; } };
Inheritence
Creating or deriving a new class using another class as a base is called inherit
ance in C++. The new class created is called a Derived class and the old class u
sed 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 d
erived 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 v
irtual 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, alth
ough not all of them will be accessible by the member functions of the derived c
lass. But there are some exceptions to it too. Some of the exceptions to be note
d 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 cl
ass 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 outsid
e the class. But a derived class is given access to protected members of the bas
e 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 an
y moving vehicles like car, bike, bus etc., class vehicle //Sample base class fo
r 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 { prote
cted: char type_of_fuel; public: Car(); }; The derived class Car will have acces
s to the protected members of the base class. It can also use the functions star
t, stop and run provided the functionalities remain the same. In case the derive
d 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 s
aid 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 point
ing. For example, to define a pointer, which will store a memory address at whic
h exists an int, we can do the following: //Sample program for c++ pointer signe
d 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 sa
y we want to define an int variable and then we want to define a pointer variabl
e, which will store the memory address of this int: //c++ pointer using an int v
ariable signed main() { int myval(7); int* p_myval; //Right now, p_myval contain
s no particular myval. p_myval = &myval; //Now, p_myval in this c++ program cont
ains 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 th
en store this int* myval in our int* variable, which is p_myval. Now, we will ac
tually use this pointer: //Sample program for c++ pointer signed main() { int my
val = 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 in
t* 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 Per
fect Team
C Sharp Tutorial B) When arrays are involved. Consider a string, an array of cha
racters: 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 Addres
s 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, t
he position of the first character will start from 0. So the array of size 4 wil
l be accessed for characters from 0, 1, 2 and 3. We can define a pointer to poin
t 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 memo
ry: Name of Variable Type of Variable Address in Memory Value Stored my_name Cha
r* 116 109 char 109 ‘o’ char 110 ‘d’ char 111 ‘e’ char 112 ‘\0’ So that’s one us
age of c++ pointers there, to point to an individual object in an array. The oth
er 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 foll
owing: // 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_p
rimate = 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** point
s to an int*. In English: The variable p_cow above stores a memory address. At t
hat memory address exists a variable of type int*. This int* variable also store
s 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++ p
ointer to pointer int main() { int cow(7); int* p_cow = &cow; int** p_p_cow(&p_c
ow); 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* c
onst 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. T
he function will return the first instance of the character ‘t’ in the string: c
har* GetFirstT(char* p_first_char) { for ( ; *p ; ++p) { if ( *p == ‘t’ ) return
p; } return 0; } signed main() { char the_alphabet[] = "abcdefghijklmnopqrstuvw
xyz"; char* p_t = GetFirstT(the_alphabet); } Now I’m going to talk about c++ poi
nters and constness. If you want a const c++ pointer variable, a c++ pointer var
iable whose value you can’t change after initialization, then stick the const di
rectly 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 prob
lem, 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 varia
ble is non-const *p_k = 7; //COMPILE ERROR } If you want a const c++ pointer tha
t points to a const variable then: signed int main() { int myval(17); int myvalu
e2 = 4; const int* const p_k = &myval; p_k = &myvalue2; //COMPILE ERROR *p_k = 3
2; //COMPILE ERROR }
SUNSAT The Perfect Team