C++ 对象模型 ch1 关于对象

1. demo

#include <iostream>

using namespace std;

class X 
{
public:
        int a;
        virtual void foo()
        {
                cout << " I am in X " << endl;
        }
};

class Y : public X
{
public:
        void foo()
        {
                cout << " I am in Y " << endl;
        }
};

void f(X x, X* x1, X& x2)
{
        x.foo();
        x1->foo();
        x2.foo();
}

int main()
{
        X x;
        X* x1 = new Y();
        cout << sizeof(x1) << endl;
        X& x2 = *x1;

        f(*x1, x1, x2);
}

2. 输出:

/home/a/j/nomad2:uname -a
FreeBSD freebsd.unix-center.net 7.2-RELEASE-p8 FreeBSD 7.2-RELEASE-p8 #0: Tue May 25 17:51:43 UTC 2010     [email protected]:/usr/obj/usr/src/sys/GENERIC  amd64
/home/a/j/nomad2:./a.out 
8
 I am in X 
 I am in Y 
 I am in Y 

3. 关于第一个调用输出X,解释如下:

When a base class object is directly initialized or assigned with a derived class object, the derived object is sliced to fit into the available memory resources of the base type. There is nothing of the derived type remaining. Polymorphism is not present, and an observant compiler can resolve an invocation of a virtual function through the object at compile time, thus by-passing the virtual mechanism. This can be a significant performance win if the virtual function is defined as inline.

你可能感兴趣的:(C++ 对象模型 ch1 关于对象)