Object-Oriented Programming in C++/ CLI

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This article elaborates the underlying object-oriented programming implementations, including inheritance interface, polymorphism, and many more in the context of C++/CLI programming. Object-oriented programming lets us build hierarchies of objects: creating them and defining how they are related. We perceive the world as consisting of objects; for example, bank accounts, arrays, files, and users, all of which are analogous to objects in the real world. Object-oriented programming is a paradigm that provides a natural way to develop many kinds of systems.

Essentials

It is expected that programmers must have proficiency in native C++ object-oriented programming, along with a deep understanding of building and executing C++ and C# applications under the .NET CLR context.

Namespace

The .NET types are organized in a special container referred to as a namespace. It can embody any types, such as class, interface, structure, properties, methods, and so forth. We have to specify the namespace keyword after usingin the header portion, if we want to reference some other assembly. We can define aliases in C++/CLI, but they can only reference other namespaces, not classes./p>

// import reference
using namespace System;
using namespace System::Text;

// alias
using abc= System::Windows::Forms;

// namespace definition
namespace test
{
   namespace ajay
   {
      namespace champu
      {
         // code...
      }
   }
	}

Class

Class encompasses both the definition of data, called ‘members,’ that makes up an object and the means of manipulating the data that belongs to individual object of the class. Classes are the specification of data type that you define, which usually contains data elements that can either be variable or other user-defined data types. Moreover, class also comprises a function called ‘member functions’ that operate on a class object by accessing its members. Overall, when you define a class, you are actually defining the blueprint for a data type that specifies the class name; that is, what an object of the class will consist of and what operations can be performed on such objects.

Defining a Class

C++/CLI has its own class types, allows two different definitions for both value and reference types, such as value class and ref class. Here, both keywords’ meaning is distinct. Value is stored in the stack and ref is stored in the heap. Moreover, it also prefixed with a combination of modifiers such as private, public, and protected; these terms determine its access behavior across the assembly or outside the assembly.

The Value class offers the possibility for you to define new primitive types that can be used in a similar way to the fundamental type. A variable of the value class type is created on the stack and stores the value directly. Here, the class defined by using value keyword contains two public members between the curly braces as shown in the following code segment:

public value class CArea
{
private:
   int height;
   int width;
public:

   ...
};

On the other hand, the heap class type can be declared by using the ref keyword that also contains the heap private variables that are stored in the heap as shown in the following code snippet:

public
  ref class CArea
{
 private:
   // heap variables (Handle of type '^')
   int^ height;
   int^ width;
public:

   ...
};

Class Instantiation

The class instantiation phase is the step during which you define the object of the class with exactly the same sort of declaration that you use to declare objects of basic types. You can refer to the data members of a class by using the direct member selection operator (.) and handle of type (^) that you used to access members of class, as follows. However, you can create an object in the heap after defining the class as a value class and vice-versa.

CTest^ oObj= gcnew CArea();  // Object creation in heap

oObj->iAge;   // Accessing members of heap class
oObj->dLength;

CTest oBj;   // Object created in stack
oObj.iAge;
oObj.dLength;

Access Control in a Class

The access modifier plays a significant role in a class, as well as in inheritance, to prevent the access of members such as variables, function, and the like, inside or outside the C++/CLI assembly. The following table depicts an overview about various access modifiers.

Keywords Description
Public All Access.
Protected The access is possible in the derived class.
Internal Protected Allows accessing the members from within the same assembly and from other assemblies if the type is derived from the base type.
Private There is no access outside the assembly.
Internal Access is possible in the same package or namespace.
Virtual Declares a method to support polymorphism.
Override Overrides a virtual method in the derived class.
New Hides a method from base class.
Classname:: References the base class.
This References the current object.
Sealed Stops a class from being inherited.

Constructor

A class constructor is a special function in a class that is called when a new object in the class is created. It, therefore, offers the opportunity to initialize objects as they are created. Besides, a class constructor may have several constructors, such as default, parameterize, and parameterless, enabling you to create objects in various ways.

ref class CArea
{
public:
   double height;
   double width;

   // Constructor
   CArea(double h, double w)
   {
      height= h;
      width= w;
   }
   double AreaCal()
   {
      return height * width;
   }
};

int main(array<System::String ^> ^args)
{
   // Constructor Invoked
   CArea^ a1= gcnew CArea(20, 4);
   Console::WriteLine(L"Area is=",
      a1->AreaCal());

   return 0;
}

However, you can add the definition of the default constructor that is one that doesn’t require any arguments to be supplied. In the previous section of code, you can default the constructor as;

CArea() {}   //default constructor
...
// Invoking default constructor
CArea^ a=gcnew CArea();

Abstract Class

The abstract classes are used to implement a C+ equivalent pure virtual function. The abstract class is defined by using the abstract keyword that allows you to create objects of that class type. It exists only for the purpose of defining classes that are derived from it. Unlike an interface, we can define the implementation (body) of a function in the abstract class. If a class derived from an abstract class, it still defines a pure virtual function of the base as pure because it, too, is an abstract class. The polymorphic method implementation must be marked with the override keyword in the derived class, as follows:

#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;
}

Interface

The interface keyword is used to define an interface. Defining an interface in C++/CLI is similar to using the C# language, but the implementation is slightly different. An interface is a class that specifies a set of functions that are to be implemented by other classes to provide a standardized way of offering some functionality. The method that is defined in the interface must be implemented with the virtual keyword in the child class, as shown in the following code segment:

public interface class IDisplay
{
   void hello();
};

public ref class test: IDisplay
{
public:
   virtual void hello()
   {
      Console::WriteLine("Hello test");
   }
};

Inheritance

Inheritance is the 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. A base class can be specified for a derived class with the keywords public, private, and protected. The base class should be followed by a colon (:) in the derived class, as follows:

public ref class baseClass
{
public:
   virtual void showBase()
   {
      Console::WriteLine("base class");
   }
};
public ref class test : baseClass
{
public:
   void showDerived()
   {
      Console::WriteLine("derived class");
   }
};
int main(array<System::String ^> ^args)
{
   test^ t=gcnew test();
   t->showBase();
   t->showDerived();
   return 0;
}

Conclusion

This article depicted object-oriented programming in the context of C++/CLI by discussing class, constructors, inheritance, and polymorphism. A class can be defined in thee stack and the heap, contains data members and function members where objects are created and initialized; these members using special functions called constructors. You have come to an understanding about inheritance, where base class members can be utilized again in a child class, and, by using polymorphism, you can redefine the behavior of a base class method in a derived class.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read