ためになるホームページ お問い合わせ




TOP > C++ > クラスの継承(3) ポインタの使用方法
クラスの継承とポインタの使用方法
基底クラスのポインタに派生クラスのオブジェクトのポインタを代入する事ができる。この時、ポインタが指せるメンバは基底クラスのメンバのみとなる。
派生クラスのメンバにはアクセスできない。基底クラスは派生クラスのメンバを知らないからである。
逆に派生クラスのポインタが基底クラスのオブジェクトを指す事はできない。

基底クラスのポインタに派生クラスのオブジェクトを代入する例
#include <iostream>
using namespace std;

class Parent
{
public:
  Parent()
  {
  }
  ~Parent(){}
  void parent_func()
  {
    cout << "基底クラスの関数です" << endl;
  }
};

class Child : public Parent
{
public:
  Child(){}
  ~Child(){}
  void child_func()
  {
    cout << "派生クラスの関数です。" << endl;
  }

};

int main(int argc, char** argv)
{
  Parent *p_parent, i_parent;
  Child i_child, *p_child;
  //コンパイルエラー
  //p_child = &i_parent;
  p_parent = &i_child;
  p_parent->parent_func();
  //コンパイルエラー
  //p_parent->child_func();

  return(0);
}







Copyright 2007 ためになるホームページ All Rights Reserved.