Visual C++ .NET/Class/Constructor
Adding Constructors
#include "stdafx.h"
using namespace System;
ref class ParentClass{
public:
ParentClass() : PVal(10) {}
ParentClass(int inVal) : PVal(inVal) {}
ParentClass(const ParentClass %p) : PVal(p.PVal) {}
int PVal;
};
ref class ChildClass : public ParentClass{
public:
ChildClass () : CVal(20) {}; // default constructor
ChildClass (int inVal1, int inVal2) : ParentClass(inVal1), CVal(inVal2) {}
ChildClass(const ChildClass %vals) : ParentClass(vals.PVal), CVal(vals.CVal) {}
int CVal;
};
void main()
{
ParentClass p1(4);
ParentClass p2 = p1; // Copy Constructor
p1.PVal = 2;
Console::WriteLine("p1.PVal=[{0}] p2.PVal=[{1}]", p1.PVal, p2.PVal);
}
Constructor inheritance
#include "stdafx.h"
using namespace System;
ref class MyBase{
int data;
public:
MyBase() { Console::WriteLine("MyBase::MyBase()"); }
MyBase(int data_in) : data(data_in) { Console::WriteLine("MyBase::MyBase(int)"); }
};
ref class Derived : MyBase
{
public:
Derived(int data) : MyBase(data)
{ Console::WriteLine("Derived::Derived(int)"); }
};
int main()
{
MyBase b;
Derived d(100);
}
Constructor order
#include "stdafx.h"
using namespace System;
class MyClass
{
public:
MyClass()
{
Console::WriteLine("MyClass: Field constructor.");
}
};
ref class MyClass2
{
public:
MyClass2()
{
Console::WriteLine("MyClass2: Field constructor.");
}
};
class MyBaseClass
{
public:
MyBaseClass()
{
Console::WriteLine("MyBaseClass: Base class constructor.");
}
};
class NativeDerived : MyBaseClass
{
MyClass field;
public:
NativeDerived() : field()
{
Console::WriteLine("Native: Derived class constructor.");
}
};
ref class ManagedBase
{
public:
ManagedBase()
{
Console::WriteLine("ManagedBase: Base class constructor.");
}
};
ref class ManagedDerived : ManagedBase
{
MyClass2 field;
public:
ManagedDerived() : field()
{
Console::WriteLine("ManagedDerived: Derived class constructor.");
}
};
int main()
{
NativeDerived nd;
ManagedDerived md;
}
public constructor
#include "stdafx.h"
using namespace System;
ref class MyClass
{
public:
literal String^ name = "Bob";
MyClass()
{
Console::WriteLine(name);
}
void Print()
{
Console::WriteLine(name);
}
};
int main()
{
MyClass^ c = gcnew MyClass();
c->Print();
Console::WriteLine( MyClass::name );
}