Encapsulation is an important concept of Object-oriented programming. Encapsulation is the concept of wrapping up data(variable) under a single unit. It binds data members and member functions inside a class together.
Encapsulation prevents accessing the implementation details, it makes sure that the ‘sensitive’ data are hidden from the user which leads to the important concept called data hiding. Abstraction and Encapsulation are quite related features, encapsulation helps us to achieve the desired level of abstraction.
Access specifiers are used to achieve encapsulation. We can do so by declaring all the variables in a class private. But in order to modify or read those data or variables, we need to use the getter and setter (i.e. get and set) method. It prevents from accessing the data directly.
Let us go through an example in C# to understand the concept of hiding data.
Example: C# program for hiding data using the private specifier
There is a separate class for the student whose data members are private so get and set methods are implemented for each private variable in order to access it from the main function of the program.
using System;
public class Student
{
// private variables
private String name;
private int roll;
// using setter and getter for name
public String stdName
{
get
{
return name;
}
set
{
name = value;
}
}
// using setter and getter for roll
public int stdRoll
{
get
{
return roll;
}
set
{
roll = value;
}
}
}
class StudentInfo
{
static public void Main()
{
// creating object
Student obj = new Student();
//setting the values
obj.stdName = "John Mac";
obj.stdRoll = 15;
// Getting the values
Console.WriteLine("Student Name: " + obj.stdName);
Console.WriteLine("Studen Roll: " + obj.stdRoll);
}
}
Output:
Student Name: John Mac Studen Roll: 15
Advantages of Encapsulation:
Data- hiding and Reusability.
The class field can be made read-only or write-only.
It provides the class the total control over the data.
Enum is also known as enumeration that consists of a set of named integral constants. In C#, enumerations are value data types. The keyword enum is used to define these data types.
The is mainly used to assign the names or string that makes the code more maintainable and readable. For example, we can create an enum for seasons (spring, summer, autumn, winter), or for days(Monday, Tuesday, ….), etc.
The constant in it is the fixed set of constants and is also known as an enumerator. Enum can also be traversed.
Syntax of enums
enum enum_name{const1, const2, ....... };
enum_name: Name of the enum given by the user.
const1, const2 : These are the value of type enum_name, separated by comma.
Let us see an example to define enum.
enum season { spring, summer, autumn, winter };
The above is the enum for the season, spring, summer, autumn and winter are the types of the season and by default, the value starts in increasing order from zero such as spring is 0, summer is 1, autumn is 2 and winter is 3.
Example 1: C# program for enum
using System;
public class EnumEg
{
public enum Season
{
Spring, Summer, Autumn, Winter
}
public static void Main()
{
int firstSeason = (int) Season.Spring;
int lastSeason = (int) Season.Winter;
Console.WriteLine("Spring: {0}", firstSeason);
Console.WriteLine("Winter: {0}", lastSeason);
}
}
Output:
Spring: 0 Winter: 3
As you can see that the default numbers assigned to the constant are shown according to the access. Spring is first on the list so it is 0 and And Winter is at fourth on the list so it is 3 (n-1, starts at 0).
Example 2: C# program for enum to change the index
We write a program to change the default indexing of constants in an enum.
using System;
public class EnumEg
{
public enum Season
{
Spring = 10, Summer, Autumn, Winter
}
public static void Main()
{
int firstSeason = (int) Season.Spring;
int secondSeason = (int) Season.Summer;
int lastSeason = (int) Season.Winter;
Console.WriteLine("Spring: {0}", firstSeason);
Console.WriteLine("Summer: {0}", secondSeason);
Console.WriteLine("Winter: {0}", lastSeason);
}
}
Output:
Spring: 10 Summer: 11 Winter: 13
Now we assign 10 to spring in the list, and from here the increment starts summer becomes 11, and so on. Also, can be seen in the output.
Example 3: C# program for enum use of getValues()
We will use getValues and get all the values present in the enum of the season.
using System;
public class EnumEg
{
public enum Season { Spring = 10, Summer, Autumn, Winter
}
public static void Main()
{
foreach(Season s in Enum.GetValues(typeof(Season)))
{
Console.WriteLine(s);
}
}
}
Struct in C# is a value type and a collection of variables of different data types inside a single unit. It is similar to classes in C# because both are the blueprints to create an object of a class and both are user-defined types.
However, a struct is a value type whereas a class is a reference type. Also, the struct does not support inheritance but can implement an interface. A class can have a default constructor whereas a struct cannot have a default constructor.
Syntax of struct in C#
Defining and Initialization struct in C#: The keyword that is used to define the structure is struct. A structure can also contain constructors, constants, fields, methods, properties, indexers, etc.
Structures can be instantiated with or without new keyword in C#.
Consider basic data of student: name, roll, score. And also let us initialized those values by creating an instance of the struct. Student structure is declared in the following way:
//Struct Defining
public struct Student
{
public string name;
public int roll;
public float score;
};
//Initialization
Student std = new Student();
std.name = "John Mac";
std.roll = 1101;
std.score = 80.5;
Let us go through an example to understand it better.
Example 1: C# program for structure
using System;
public struct Student
{
public string name;
public int roll;
public float score;
};
public class StructureEg
{
public static void Main(string[] args)
{
Student std = new Student();
std.name = "John Mac";
std.roll = 1101;
std.score = 80.5 f;
Console.WriteLine("Name: {0}", std.name);
Console.WriteLine("Roll: {0}", std.roll);
Console.WriteLine("score: {0}", std.score);
}
}
Output:
Name: John Mac Roll: 1101 score: 80.5
Example 2: C# program for structure using constructor and methods
It is another program where we will use a constructor and create a method for a structure.
using System;
public struct Student
{
public string name;
public int roll;
public float score;
//constructor
public Student(string n, int r, float s)
{
name = n;
roll = r;
score = s;
}
//Method
public void display()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Roll: {0}", roll);
Console.WriteLine("score: {0}", score);
}
};
public class StructureEg
{
public static void Main(string[] args)
{
Student std = new Student("John Mac", 1101, 80.5 f);
std.display();
}
}
Output: The result is the same as example 1 above.
Static is a keyword in C# that is when used with different to declare static classes and static class members. Static can be field, method, constructor, class, properties, operator, and event. The instance of a class is not required in order to access static members.
There is only one copy of the object is created for the static members and is shared among all the objects. Let see the use of static in three areas of the program:
static field
static method
static class
C# Static Variable or field
The variable or field in class when declared static is called static field. The difference between static and instance fields is, no matter how many times you create an object for the class, there will be only one memory allocated for the static field of the class and is shared by all the objects.
But in the case of the instance field, with the creation of every object of the class, a new memory is allocated for the instance field for each object.
Example: C# example for the static field.
using System;
class StaticExample
{
public static int temp;
public void counter()
{
temp++;
}
public int getTemp()
{
return temp;
}
}
class StaticMain
{
static void Main(string[] args)
{
StaticExample st1 = new StaticExample();
StaticExample st2 = new StaticExample();
st1.counter();
st1.counter();
st2.counter();
st2.counter();
Console.WriteLine("Temp count for st1: {0}", st1.getTemp());
Console.WriteLine("Temp count for st2: {0}", st2.getTemp());
}
}
Output:
Temp count for st1: 4 Temp count for st2: 4
As you can see, no matter which object you use to call, the temp keeps increasing. This indicated that the static field has only one instance and is used by all the other objects.
C# Static Methods
The methods that are declared with a static keyword are called static methods. This method can only access the static field of the class.
Just like a static field, the static function also does not depend on the object of the class. Let us see an example.
Example: C# example for the static method.
using System;
class StaticExample
{
public static int temp;
public void counter()
{
temp++;
}
public static int getTemp()
{
return temp;
}
}
class StaticMain
{
static void Main(string[] args)
{
StaticExample st = new StaticExample();
st.counter();
st.counter();
Console.WriteLine("Temp count for st: {0}", StaticExample.getTemp());
}
}
Output:
Temp count for st: 2
Also, note that the static method can not be invoked with the object of the class. The class name itself is used to invoke the static method. In the above eg. StaticExample.getTemp() is used to invoke the static method getTemp().
C# static class
The static class in C# is cannot be instantiated. It can only have static members in its body. And it is created using a static keyword in front of the class like the static field and method.
Following are some points to remember about static class.
The instance of static class cannot be created.
To access static members, a class name is used which is followed by the member name.
It only has static members and canoot be intatiated.
Syntax of static class
public static class class_name
{
//static data members
//static methods
}
Example: C# example for the static class.
using System;
namespace Program
{
public static class Square
{
//static fields
public static int side = 10;
//static method
public static void area()
{
Console.WriteLine("Area of a square: " + side *side);
}
}
class StaticMain
{
static void Main(string[] args)
{
Console.WriteLine("Side of a square: " + Square.side);
Square.area();
}
}
}
In C#, this is a keyword that refers to the current instance of a class. It is also used to pass the object to another method as a parameter and also used to call a constructor of another class from the same class in a program.
It is used to access members from the constructors, instance methods, and instance accessors.
Let us see an example of this keyword in C# programming.
Example: C# program for this keyword
using System;
namespace program
{
public class Student
{
public int roll;
public String name;
public int age;
public String subject;
//constructor
public Student(int r, String n, int a, String sub)
{
this.roll = r;
this.name = n;
this.age = a;
this.subject = sub;
}
public void display()
{
Console.WriteLine(roll + " " + name + " " + age + " " + subject);
}
}
class StudenInfo
{
public static void Main(string[] args)
{
Student std1 = new Student(1101, "Shaun", 19, "Maths");
Student std2 = new Student(1102, "Garen", 17, "Computer");
Student std3 = new Student(1103, "Parker", 18, "Biology");
std1.display();
std2.display();
std3.display();
}
}
}
A destructor is the opposite of a constructor. A destructor destroys the object of a class as soon as the scope of an object ends. It is also invoked automatically just like a constructor.
The destructor cannot have parameters nor modifiers.
Syntax of destructor in C#
The destructor has the exact same name as the class, the difference is, it is prefixed with a tilde sign (~).
//Syntax
~ClassName()
//Example
using System;
namespace program
{
class Square
{
~Square() // destructor
{
// statement
}
}
}
let us see an example of a destructor in C#.
Example of constructor and destructor in C#
using System;
namespace program
{
public class Student
{
public int roll;
public String name;
public float score;
//constructor
public Student(int r, String n, float s)
{
roll = r;
name = n;
score = s;
}
public void display()
{
Console.WriteLine(roll + " " + name + " " + score);
}
//Destructor
~Student()
{
Console.WriteLine("Destructor invoked");
}
}
class StudenInfo
{
public static void Main(string[] args)
{
Student std1 = new Student(1101, "Shaun", 80.5 f);
Student std2 = new Student(1102, "Garen", 90 f);
std1.display();
std2.display();
}
}
}
In C#, a constructor is the member of the class and is automatically invoked once the object of the class is created. It is like a method in a program and is used for the initialization of the data members of a newly created object.
class Example
{
.......
// Constructor
public Example() {
//Object initialization
}
.......
}
//creating oject
Example obj = new Example();
Two types of C#constructors
Default constructor
Parameterized constructor
Default Constructor in C#
A constructor without any parameters is called a default constructor and is invoked at the time of creating the object of the class.
Example: Default C# Constructor
using System;
public class Student
{
public Student()
{
Console.WriteLine("Constructor Called");
}
public static void Main(string[] args)
{
Student std1 = new Student();
Student std2 = new Student();
}
}
Output:
Constructor Called Constructor Called
As you can see, that the constructor is called every time we create a new object of the class. And since it is a default constructor, it has no parameter.
Parameterized Constructor in C#
A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign a different initial value to distinct objects.
Example: Parameterized C# Constructor
using System;
public class Student
{
public int roll;
public String name;
public float score;
//constructor
public Student(int r, String n, float s)
{
roll = r;
name = n;
score = s;
}
public void display()
{
Console.WriteLine(roll + " " + name + " " + score);
}
}
class StudenInfo
{
public static void Main(string[] args)
{
Student std1 = new Student(1101, "Shaun", 80.5f);
Student std2 = new Student(1102, "Garen", 90f);
std1.display();
std2.display();
}
}
Output:
1101 Shaun 80.5 1102 Garen 90
As you can see the student details are initialized and displayed for every object created for the Student class in a program.
C# is an object-oriented programming language and classes and objects are the fundamental components of OOP’s. Everything in C# is built upon classes and objects. Let us learn classes and objects with an example.
C# Class
A class is a user-defined blueprint or prototype for creating Objects. We can say that it is a template for creating objects for a class.
A class can have fields, methods, constructors, etc and these members can be accessed and used by creating an instance of that class that is an object.
Example for defining a class with few fields and methods in C#.
public class Rectangle
{
//field
int length, breadth;
int area;
// method
public void area() {
area = length * breadth;
}
}
The definition of the class starts with the keyword class followed by a class name. The body of the class is enclosed within the curly brace. All the members of the class are declared within the body of the class as shown above.
C# Object
Objects are real-world entities. Example bike, Lamp, pen, table, etc. It is an instance of a class that has states and behavior. It can be physical and logical.
The Class members are accessed by creating an object of that class and is a runtime entity created at runtime.
To create an object of a class we use the keyword new.
//creating an object of class Rectangle
Rectangle rect = new Rectangle();
In the above code, Rectangle is a type and rect is a reference variable that refers to the instance of the Rectangle class. And the new keyword allocates the memory at runtime in a program.
Example1: C# Class and Object
Let see an example where we create a class Rectangle and have a method calculate the area and also display the area value.
using System;
public class Rectangle
{
//field
int length = 2, breadth = 3;
int area;
// method
public void areaFunc()
{
area = length * breadth;
Console.WriteLine("Area: {0}", area);
}
public static void Main(string[] args)
{
Rectangle rect = new Rectangle(); //object
rect.areaFunc();
}
}
Output:
Area: 6
Example1: C# Class and Object
In the example below, we will put the main method at the different classes and create multiple objects for the Student class. Also, display the student information.
using System;
public class Student
{
//field
int roll = 2;
String name;
//Constructor
public Student (int r, String str)
{
this.roll = r;
this.name = str;
}
// method
public void display()
{
Console.WriteLine("Roll: {0}, Name: {1}", roll, name);
}
}
class StudentInfo
{
public static void Main(string[] args)
{
Student std1 = new Student(1, "John Mac"); //object
Student std2 = new Student(2, "Ryan Blanc"); //object
std1.display();
std2.display();
}
}
Output:
Roll: 1, Name: John Mac Roll: 2, Name: Ryan Blanc
Also, a constructor is included in order to initialize the class field.
An exception is an event or an error that arises during the execution of a program i.e. during run–time. The occurrence of an exception in a program disrupts the normal flow of instructions.
So to handle such errors, we use exception handlers. If we do not handle the exception properly then the program may terminate. We can catch an exception through exception handling and our program will not completely terminate.
The main advantage of exception handling is to ensure that even when an exception occurs, the program’s flow doesn’t break.
C++ Exception Handling Keywords
C++ provides three keywords to perform exception handling. They are:
try: The try block identifies the block of code for which the exception will be activated. It is followed by a catch block.
catch: The catch indicates the cathching of an exception where you want to catch the error accuring in the program.
throw: throw keyword is used to throw an exception when a problem arises in a program.
try/catch in C++
Assume that the block of code will cause an error and you want to catch that exception. The try and catch block will help you to do that. You place a code inside the try block which you think causing the problem and catch the statement to catch the exception.
We can place a multiple catch statement on different types of exceptions that may arise by try block code.
Example: C++ try/catch
Use of try, catch and throw keywords in a C++ program.
#include <iostream>
using namespace std;
double division(int x, int y)
{
if (y == 0)
throw "Division by Zero attempted.";
return (x / y);
}
int main()
{
int a = 11;
int b = 0;
double c = 0;
try
{
c = division(a, b);
cout << c << endl;
}
catch (const char *ex)
{
cerr << ex << endl;
}
return 0;
}
Output:
Division by Zero attempted.
C++ Standard Exceptions
C++ provides a list of standard exceptions defined in <exception> class that we can use in a program.
These exceptions and descriptions are listed in the table below.
Exception
Description
std::exception
This is an exception and the parent class of all standard C++ exceptions.
std::bad_alloc
This can be thrown by a keyword new.
std::bad_cast
This can be thrown by dynamic_cast.
std::bad_exception
A useful device for handling unexpected exceptions in C++ programs.
std::bad_typeid
An exception thrown by typeid.
std::logic_error
This exception is theoretically detectable by reading code.
std::domain_error
This is an exception thrown after using a mathematically invalid domain.
std::invalid_argument
This exception is thrown for using invalid arguments.
std::length_error
This exception is thrown after creating a big std::string.
std::out_of_range
Thrown by at method.
std::runtime_error
This is an exception that cannot be detected via reading the code.
std::overflow_error
This exception is thrown after the occurrence of a mathematical overflow.
std::range_error
This exception is thrown when you attempt to store an out-of-range value.
std::underflow_error
This exception is thrown after the occurrence of mathematical underflow.
User-Defined Exceptions
The C++ std::exception class allows us to define objects that can be thrown as exceptions. This new exception can be defined by overriding and inheriting the exception class functionality. This class has been defined in the <exception> header.
Example: user-defined exception in c++
#include <iostream>
#include <exception>
using namespace std;
class ExceptionEg: public exception
{
virtual
const char *what() const
throw ()
{
return "Occurance of new exception";
}
};
int main()
{
ExceptionEg newEx;
try
{
throw newEx;
}
catch (exception & ex)
{
cout << ex.what() << '\n';
}
return 0;
}
A string is a sequence of characters that is an object of std::string class in C++. Memory to a string is allocated dynamically that is we can assign memory during runtime as required. Various operations are performed on a string such as concatenation, comparison, conversion, etc.
C++ supports two types of string in a program.
C-style character string.
String class type (Standard C++ Library).
C-style character string
C-style was introduced in the C programming language and is continued to be supported by C++. These one-dimensional strings are stored in a series in an array of type char and are terminated by a null character ‘\0’.
Memory presentation of the character array in C/C++:
Declaring C-style string:
char name[5] = {'A', 'l', 'e', 'x', '\0'};
The above character for a string ‘Alex‘. But notice that the number f character is 4 but we declare the size 5 as because the last space is reserved for the null character in order to terminate the string.
Although, we can also initialize the above in the following way.
char name[] = "John";
Note that here, we do not have to add a null character at the end. The C++ compiler will automatically place the ‘\0‘ at the end of the string.
Example:C++ program to read and display the string
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);
cout << "Entered String is: " << str << endl;
return 0;
}
Enter a string: This is simple2code.com Entered String is: This is simple2code.com
Notice that we use cin.get in order to get the string from the user that contains white spaces in a string. It takes two argument name of a string and the size of an array.
String class type
The standard C++ library provides a string class that supports the various operation on a string. It is written as std::string.
Also, instead of char type, we create a string object to hold the string. It does not require fined length like in char type, we can extend the character according to our need.
Now in order to use the class to perform various operations on a string, we need to include the following header file.
#include<cstring>
Example:C++ program to read and display the stringusing string object
Before performing on class type with some operation, let us first see a simple example of string using its object.
#include <iostream>
using namespace std;
int main()
{
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << "Entered String is: " << str << endl;
return 0;
}
Enter a string: This is simple2code.com Entered String is: This is simple2code.com
Notice that to get the string from the user, we use getline() function that takes two arguments – input stream (cin) and location of the line to be stored (str).
C++ String Functions
There are different functions provided by the string class to manipulate strings in a program. The cstring class defines these functions and we need to include cstring header file in a program. Let us see some of these functions with examples.
Function
Description
strcpy(str1, str2);
It copies string2 content in string1.
strcmp(str1, str2);
It is a comparison function. returns 0, if str1 = str2 returns less than 0, if str1<str2 returns greater than 0, if str1>str2
strcat(str1, str2);
It joins str2 into the end of str1.
strlen(str);
It returns the length of the string passed.
Example of the above string function in C++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[10] = "Mark";
char str2[10] = "John";
char str3[10];
int len;
//copy string2 to string3
strcpy(str3, str2);
cout << "strcpy( str3, str2) : " << str3 << endl;
//concatinate string1 and string2
strcat(str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
//length of a string1
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
//compare: returns 0 since str2 = str3
cout << "strcmp(str2, str3) : " << strcmp(str2, str3) << endl;
return 0;
}
We pass the string in a similar way like we pass an array to a function. We will see an example where we will learn to pass two different strings in a function.
It is a basic example, where we create two print functions and take the user input for two different strings.