You can visit the previous part of the article here:
In this session, you will learn about:
- Creating objects
- Initializing and De-initializing objects
- Creating constructors with parameters
- Life cycle of an object
- Conditional and decisional loops
Creating Object
When an object is created, the required amount of memory is allocated to it. This memory can be freed, when the object is no longer required.
The following table shows how a class is instantiated in C# and C++.
C#
- class Math
- {... < member variables > void add()
- {... < function body >
- }
- public static void Main(string[] args)
- {
- Math obj = new Math();
- obj.add();
- }
- }
C++ - class Math
- {... < member variables > public: void add()
- {... < function body >
- }
- };
- void main()
- {
- Math obj;
- Math.add();
- }
The following table shows access specifier in C# and C++.
C#
- Public
- Private
- Protected
- Internal
- Protected Internal
C++
Initializing and Deinitializing Objects
While creating an object, you may want to initialize its member variables.
How did you achieve this task in C#?
The following table shows the declaration of a constructor in C# and C++.
C#
- class Math
- {
- int number1, number2;
- public Math()
- {
- number1 = 10;
- number2 = 3;
- }
- }
C++ - class Math
- {
- int number1, number2;
- public: Math()
- {
- number1 = 10;
- number2 = 3;
- }
- };
Note that the name of the class and constructor are always the same.
In the preceding example, the member variables are initialized during program creation.
However, there exist situations when you need to initialize variables with the user supplied values. For this, you need to pass the user input to the constructor using parameters.
Constructor with Parameters
The following table shows the use of constructors with parameters in C# and C++.
C# - class Calculator
- {
- static int number1, number2;
- Calculator(int x, int y)
- {
- number1 = x;
- number2 = y;
- }
- public static void Main(string[] args)
- {
- int var1, var2;
-
-
- Calculator C1 = new
- Calculator(var1, var2);
- }
- }
C++ - class Calculator
- {
- private: int number1, number2,
- public: Calculator(int x, int y)
- {
- number1 = x;
- number2 = y;
- }
- };
- void main()
- {
- int var1, var2;
-
-
- Calculator c1(var1, var2);
- }
Destructors
When an object goes out of scope, the memory allocated to the object needs to be freed. And this is done through destructors.
The following table shows the declaration of a destructor in C# and C++.
C# - class Calculator
- {
- Calculator()
- {
- Console.WriteLine(“Constructor Invoked”);
- }~Calculator()
- {
- Console.WriteLine(“Destructor Invoked”);
- }
- }
C++ - class Calculator
- {
- public: Calculator()
- {
- cout << “Constructor Invoked”;
- }~Calculator()
- {
- cout << “Destructor Invoked”;
- }
- };
Note that the destructor has the same name as its class but prefixed with a ~ (tilde) symbol.
Conditional and Looping Constructs Conditional constructs used in C# and C++
Looping constructs used in C# and C++