Thread: Segmentation fault on accessing virtual function of base class by base class pointer

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    76

    Segmentation fault on accessing virtual function of base class by base class pointer

    Code:
    #include<iostream>
    using namespace std;
    class A
    {
            public:
            virtual void s()
            {
                    cout<<"I am in A"<<endl;
            }
    };
    class B:public A
    {
            public:
            void s()
            {
                    cout<<"I am in B"<<endl;
            }
    };
    int main()
    {
            A *o;
            o->s();                                  //Problem
            B ob;
            o=&ob;
            o->s();
            return 0;
    }
    Though that virtual function is accessible if I call it inside derived class' s(); using scope resolution, i.e.:

    Code:
     void s()
            {
                    A::s();
                    cout<<"I am in B"<<endl;
            }
    Why can't I call base class (A's) virtual function by base class pointer?
    Last edited by gaurav#; 01-24-2016 at 04:33 AM.

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    'o' is not pointing to anything (well, technically it's pointing to an undefined location)

  3. #3
    Registered User
    Join Date
    Jan 2014
    Posts
    76
    isn't o pointing to location of s() of base location?

  4. #4
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Quote Originally Posted by gaurav# View Post
    isn't o pointing to location of s() of base location?
    No, you have to initialise it to point to an object. E.g.

    Code:
            A foo;
            A *o = &foo;
    
            o->s();

  5. #5
    Registered User
    Join Date
    Jan 2014
    Posts
    76
    Sorry, that was real basic I've missed!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calling base class function when base is a template
    By VirtualAce in forum C++ Programming
    Replies: 9
    Last Post: 07-11-2010, 02:26 AM
  2. Base Class Overloaded Virtual Function
    By leeor_net in forum C++ Programming
    Replies: 11
    Last Post: 07-13-2009, 06:37 AM
  3. Base-class pointer, accessing object from derived class
    By Korhedron in forum C++ Programming
    Replies: 15
    Last Post: 09-28-2008, 05:30 AM
  4. Replies: 2
    Last Post: 04-06-2005, 07:25 AM
  5. virtual function in base class
    By QueSue in forum C++ Programming
    Replies: 12
    Last Post: 01-25-2003, 05:27 PM