dynamic_cast requires virtual functions (polymorphic), why?


First of all, if you ALREADY know the cast is safe, static_cast can replace dynamic_cast, even in mutilple inheritance, except virtual inheritance.
Please see this post for why.

struct D: virtual B {...};//have to use dynamic_cast to cast B* to D*

I have to go through a few steps to explain this.
1. dynamic_cast needs access to RTTI (again, the above link says why).
2. RTTI is only accessable through vtable pointer.
3. no virtual functions, no vtable pointer. (RTTI can sit right above vtable)
4. Conclusion, dynamic_cast needs virtual function.

Advertisements

A minimum iterator template that works with ostream_iterator


This iterator works with std::ostream_iterator to get the container’s content printed to cout.
It’s minimum because it stops working if I take one more element out.
Minimum snippets is best to show how things work under the hood.

template <class T> class CMyContainer
{
public:
	enum {MAX = 2}; //only hold two elements
protected:
    T maData[MAX];
public:
    CMyContainer<T>(const T& t1, const T& t2)
	{
		maData[0] = t1; maData[1] = t2; //pre-initialized to only 2 element
	}
    class iterator;
    iterator begin()
	{
		return iterator(0, this);
	}
    iterator end()
	{
		return iterator(MAX, this);
	}
};
template <class T> class CMyContainer<T>::iterator
{
    CMyContainer<T> * mpContainer;
    int miIndex;
public:
	typedef std::forward_iterator_tag iterator_category;
	typedef void value_type;
	typedef void difference_type;
	typedef void distance_type;
	typedef void pointer;
	typedef void reference;
    iterator () {}
    iterator (int iIndex, CMyContainer<T> * c): miIndex(iIndex), mpContainer(c) {}
    bool operator==(const iterator & z)
	{
		return miIndex == z.miIndex;
	}
    bool operator!=(const iterator & z)
	{
		return !operator==(z);
	}
    void operator++()
	{
		++ miIndex;
    }
    T& operator*()
	{
		return mpContainer->maData[miIndex];
	}
};

void TestCustomIterator()
{
	CMyContainer<int> b(1, 2);
	CMyContainer<int>::iterator it;
	ostream_iterator<int> o(cout, " ");
	copy(b.begin(), b.end(), o); //this line prints 1 2 (content of b)
}

What’s the default inheritance type when ‘struct’ derived from ‘class’?


Dose this piece of code compile?

class CBase
{
public:
	void b() {	}
};
struct CSub: CBase //default inheritance
{
};
void TestInheritance()
{
	CSub Sub;
	Sub.b();

}

Yes. The default inheritance is public as long as the derived is ‘struct’ regardless of base calss.

How to define a member function pointer?


Here I define a pointer pMember pointing to CMyClass::MemberFunc and use it to call the function.

struct CMyClass
{
	int MemberFunc(char c)
	{
		return c;
	};
};
void test()
{
	CMyClass MyClass;
	int (CMyClass::*pMember)(char) = &CMyClass::MemberFunc;
	int iMember = (MyClass.*pMember)(2);
}