Before reading this article, I highly recommend reading the previous part:
Abstract
This part outlines the rest of C++/CLI Object Oriented Programming features such as inheritance, interface and polymorphism. We will learn the various control statements such as if, while and do-while constructs as well as other diverse looping constructs in detail such as for loop and switch constructs by applying C++/CLI semantics under the CLR execution model. Apart from that, we would be confronted with other significant notions such as exception handling, memory management, delegates and generics. Finally, this article illustrates how to mix the implementation of native C++ code with managed C++/CLI code under the CLR context.
Control Statements
Control statements define what code should executed from given statements. C++/CLI proposed if/else, conditional operator and Switch construct as control statements. The if/else construct syntax is very similar to C# coding as in the following.
- #include "stdafx.h"
- using namespace System;
-
- int main(array<System::String ^> ^args)
- {
- wchar_t ltr;
- Console::WriteLine("Enter the Letter");
- ltr= Console::Read();
- if (ltr >='a')
- if(ltr<='z')
- {
- Console::WriteLine("you have entered small Letter");
- }
- if (ltr >='A')
- if(ltr<='Z')
- {
- Console::WriteLine("you have entered capital Letter");
- }
- return 0;
- }
The conditional operator in C++/CLI is known as a ternary operator. The first argument must be a Boolean result; if the result is true, the first expression is evaluated; otherwise, the second one is, as in the following:
- String^ str= i>5 ? "India" : "USA";
The switch construct is very similar to C# but with the difference that C++/CLI does not support a string in the case selection. Instead we need to use an if/else construct. The following is a simple sample of this construct:
- wchar_t days;
- Console::WriteLine("1 = Sunday");
- Console::WriteLine("2 = Monday");
- Console::WriteLine("3 = Tuesday");
-
- Console::WriteLine("Enter your choice");
- days= Console::Read();
- switch(days)
- {
- case '1': Console::WriteLine("Sunday");
- break;
- case '2': Console::WriteLine("Monday");
- break;
- case '3': Console::WriteLine("Tuesday");
- break;
- default: Console::WriteLine("Out of Reach");
- break;
- }
Loop Construct
C++/CLI defines for, for each, while and do-while loop constructs. With loops, the code is repeatedly executed until a condition is met. The for, while and do-while constructs are syntactically similar to C# as in the following:
-
- for(int i=0;i<5;i++)
- {
-
- }
-
- int x=0;
- while(x<3)
- {
-
- }
-
- do
- {
-
- }while(i<3);
The for each loop is in C++/CLI. It doesn't exist with ANSI C++ because it requires the IEnumerable interface.
- array<int>^ arry= {1,2,3,4,5};
-
- foreach(int x in arry)
- {
- Console::WriteLine(x);
- }
ArraysThe C++/CLI introduced an array keyword to implement Arrays. This keyword uses a generic like syntax with angle brackets. The angle brackets are used to define the type of elements. C++/CLI supports array initializers with the same syntax as C#.
- #include "stdafx.h"
- using namespace System;
-
- int main(array<System::String ^> ^args)
- {
-
- array<int>^ a1={ 10,20,30,40,50 };
-
- for each(int i in a1)
- {
- Console::WriteLine(i);
- }
- Console::ReadLine();
- return 0;
- }
Static Members
The static members can be defined by the static keyword much like C#. A static field is instantiated only once for all objects of the type. We don't need to instantiate the class to access the static members. Instead we can directly access them using the class type name followed by "::" operator as (as in C# using the "." operator).
- #include "stdafx.h"
- using namespace System;
-
- public ref class test
- {
- public:
- static int i;
- test()
- {
- i++;
- Console::WriteLine("Constructor Called :{0}",i);
- }
- };
-
- int main(array<System::String ^> ^args)
- {
- test^ obj=gcnew test();
- test^ obj1=gcnew test();
-
- Console::WriteLine(test::i);
- Console::Read();
- return 0;
- }
Interface
The interface keyword is used to define an interface. Defining an interface in C++/CLI is similar to the C# language but the implementation is slightly different. The method that is defined in the interface must be implemented with virtual keyword in the child class as in the following:
- public interface class IDisplay
- {
- void hello();
- };
-
- public ref class test: IDisplay
- {
- public:
- virtual void hello()
- {
- Console::WriteLine("Hello test");
- }
- };
Inheritance
Inheritance is a mechanism in which base class members can be accessed in its corresponding derived class. All the C++/CLI classes are derived classes by default. This is because both value and reference classes have a standard base class System::Object. The base class should by followed by a colon (:) in the derived class as in the following:
- public ref class baseClass
- {
- public:
- virtual void showBase()
- {
- Console::WriteLine("base class");
- }
- };
- public ref class test : baseClass
- {
- public:
- void showDerived()
- {
- Console::WriteLine("derieved class");
- }
- };
- int main(array<System::String ^> ^args)
- {
- test^ t=gcnew test();
- t->showBase();
- t->showDerived();
- return 0;
- }
The access modifier portrays significant roles in inheritance in order to prevent the access of members inside or outside the assembly.
Abstract class
The abstract classes are used to implement C++ equivalent pure virtual functions. An abstract class is defined by the abstract keyword that prevents you from creating objects of that class type. Unlike interface, we can define the implementation (body) of a function in the abstract class. The polymorphic method implementation must be marked with the override keyword in the derived class as in the following:
- #include "stdafx.h"
- using namespace System;
-
- public ref class absClass abstract
- {
- public:
- virtual double square(int x) abstract;
- virtual void show()
- {
- Console::WriteLine("showing you in abstract class");
- }
- };
- public ref class test : absClass
- {
- public:
- virtual double square(int x) override
- {
- return x*x;
- }
- virtual void show() override
- {
- Console::WriteLine("showing you in derived class");
- }
- };
- int main(array<System::String ^> ^args)
- {
- test^ t=gcnew test();
- Console::WriteLine("square is= {0}",t->square(20));
- t->show();
- Console::Read();
- return 0;
- }
Exception Handling
The C++/CLI defines try, catch, throw and finally keywords to handle all the run time errors in the code segments. The exception handling implementation is very similar to other CLR supported languages. The following sample handles the array out of bounds error by employing exception handling.
- int main(array<System::String ^> ^args)
- {
- array<int>^ arry= {1,2,3};
-
- try
- {
- for(int i=0;i<=arry->Length;i++)
- {
- Console::WriteLine(arry[i]);
- }
- }
- catch(Exception^ ex)
- {
- Console::WriteLine(ex);
- }
- finally
- {
- Console::WriteLine("Exection Done");
- }
- Console::Read();
- return 0;
- }
The previous sample throws a run time exception that is handled by a try/catch block as in the following:
Delegates
Delegates are special type-safe pointers to methods. They are defined by the
delegate keyword in the C++/CLI language as in the following:
- #include "stdafx.h"
- using namespace System;
-
-
- public delegate void testDel(int z);
-
- public ref class test
- {
- public:
- void square(int x)
- {
- Console::WriteLine("Square is=",x*x);
- }
- };
-
- int main(array<System::String ^> ^args)
- {
- test^ t=gcnew test();
- testDel^ td=gcnew testDel(t,&test::square);
- td(2);
- Console::Read();
- return 0;
- }
Generics Function
Generic functions appear to do the same thing that C++ function templates do. A generic function specification is itself compiled and when you call a function that matches the generic function specification, the actual type is substituted for the type parameters at execution time. No extra code is generated at compile time.
To define delegates, C++/CLI uses the C++ like angle bracket using type parameters that are replaced by the actual type when the function is called as in the following.
- #include "stdafx.h"
- using namespace System;
-
- generic<typename T> where T:IComparable
- T MaxElement(array<T>^ x)
- {
- T max=x[0];
- for(int i=1; i< x->Length; i++)
- {
- if(max-> CompareTo(x[i]) < 0)
- {
- max=x[i];
- }
- }
-
- return max;
- }
-
- int main(array<System::String ^> ^args)
- {
- array<int>^ iData= {3, 20, 4, 12, 7, 9};
- int maxI= MaxElement(iData);
- Console::WriteLine("Max Integer is={0}",maxI);
-
- array<double>^ dData= {4.2, 2.12, 25.7,1.1};
- double maxD= MaxElement(dData);
- Console::WriteLine("Max Double is={0}",maxD);
-
- Console::Read();
- return 0;
- }
The previous sample produces a maximum number from an array using a generic function in which the type is not defined. Instead the type, such as integer or double, is defined during execution as in the following.
Resource Management
The C++/CLI code cleans the memory resources by defining the destructor that implicitly called the IDisposable interface.
- public ref class test
- {
- public:
- ~test()
- {
-
- }
- };
The C# using statement releases the resources as soon as it is no longer used. The compile implicitly creates a try/finally statement and invokes the Dispose() method inside the finally block. The C++/CLI also offers this approach but handles this in a more elegant way as in the following:
- public ref class test
- {
- public:
- void hello()
- {
- Console::WriteLine("Hello test");
- }
- };
- int main(array<System::String ^> ^args)
- {
-
- {
- test t;
- t.hello();
- }
- Console::Read();
- return 0;
- }
Native and Managed Code Mixing
The C++/CLI offers a big advantages by allowing the mixture of native C++ code with CLR managed code. This term is referred to as "It just works" in C++/CLI. The following sample illustrates the mixed code by calling the cout method of the native C++ iostream namespace as in the following:
- #include "stdafx.h"
- #include <iostream>
- using namespace System;
-
- public ref class test
- {
- public:
- void managedCode()
- {
- Console::WriteLine("Hello test");
- }
-
- void nativeCode()
- {
- std::cout << "native code sample";
- }
- };
- int main(array<System::String ^> ^args)
- {
-
- {
- test t;
- t.managedCode();
- t.nativeCode();
- }
- return 0;
- }
Summary
It is not possible to cover each and every C++/CLI concept in detail in a single article. This article outlines the ohter significant topics such as arrays, control statements, generics, delegates and conditional statements in details by defining their semantics. We also come to understand the C++/CLI OOP concepts such as interface, polymorphism and inheritance with some examples. After finishing this series of articles, one is able to write code in C++/CLI efficiently.