////////////////////////////////////////////////////////////////
// MSDN Magazine ¡ª November 2004
// To compile:
// cl /clr VirtFnTest.cpp
//
#include <stdio.h>
#include <vcclr.h>
#using <mscorlib.dll>
using namespace System;
/////////////////
// C++ native base class. Ctor calls virtual fn: always calls Base fn.
class Base {
public:
Base()
{
printf(" Base::ctor\n");
Hello();
}
~Base()
{
printf(" Base::dtor\n");
Goodbye();
}
virtual void Hello() { printf(" Base::Hello\n"); }
virtual void Goodbye() { printf(" Base::Goodbye\n"); }
};
// Derived native C++ class overrides fn, but not called from ctor.
class Derived : public Base {
public:
Derived()
{
printf(" Derived::ctor\n");
}
~Derived()
{
printf(" Derived::dtor\n");
}
virtual void Hello() { printf(" Derived::Hello\n"); }
virtual void Goodbye() { printf(" Derived::Goodbye\n"); }
};
// Managed base class. Ctor calls virtual fn: always calls most derived
// override.
public __gc class MBase {
public:
MBase() {
printf(" Base::ctor\n");
Hello();
}
~MBase() {
printf(" Base::dtor\n");
Goodbye();
}
virtual void Hello() { printf(" Base::Hello\n"); }
virtual void Goodbye() { printf(" Base::Goodbye\n"); }
};
// Managed derived class overrides virtual fn.
public __gc class MDerived : public MBase {
public:
MDerived()
{
printf(" Derived::ctor\n");
}
~MDerived()
{
printf(" Derived::dtor\n");
}
virtual void Hello() { printf(" Derived::Hello\n"); }
virtual void Goodbye() { printf(" Derived::Goodbye\n"); }
};
int main()
{
printf("Create native object:\n");
Derived *pd = new Derived();
printf("Destroy native object:\n");
delete pd;
printf("\nCreate managed object:\n");
MDerived *pmd = new MDerived();
printf("Destroy managed object:\n");
delete pmd; // force dtor call
return 0;
}
Figure 3 Pod.cpp
¡¡
/////////////////////////////////////////////////////////////////////
// You can embed native POD types in a managed (__gc or __value) type.
// Compile with cl /clr.
#using <mscorlib.dll>
// simple struct is a POD type
struct POINT {
int x;
int y;
};
// native class w/ctor: not POD!
class CPoint : public POINT {
CPoint() { x=y=0; }
};
// Managed __gc type
__gc class Circle {
public:
POINT center; // ok: embedded POD type
CPoint m_center; // Error: not POD!
int radius;
};