1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Virtual Functions and pointers

Discussion in 'C++' started by Spogliani, Jul 11, 2008.

  1. Spogliani

    Spogliani New Member

    Joined:
    Jun 24, 2008
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Milano, Italy
    Hi to everyone:)

    I'm writing this post because I have some problems accessing a function of a class through a pointer.

    This is the situation:
    I have a pointer to a class. The class inherits two virtual functions from an abstract base class.

    The problem is the following:
    When I try to call the function from the pointer I receive the following error at run-time: "Unhandled exception at 0x004251d8 in MyApplication.exe: 0xC0000005: Access violation reading location 0x00000000."

    Can somebody help me, please?

    here the declaration of the pointer and the functions:
    Code:
    [COLOR=green]//baseclass.h[/COLOR]
    [COLOR=blue]class[/COLOR] MyBaseClass
    {
    [COLOR=blue]public[/COLOR]:
      [COLOR=blue]virtual void[/COLOR] Start() = 0;
      [COLOR=blue]virtual void[/COLOR] Stop() = 0;
    };
    [COLOR=green]//class.h[/COLOR]
    [COLOR=blue]class[/COLOR] MyClass : [COLOR=blue]public[/COLOR] MyBaseClass
    {
    [COLOR=blue]public:[/COLOR]
      MyClass();
      [COLOR=blue]void [/COLOR]Stop();
    };
    [COLOR=green]//pointer[/COLOR]
    [COLOR=blue]static[/COLOR] MyClass *MyClassptr;
     
    [COLOR=green]//myclass.cpp[/COLOR]
    MyClass::MyClass()
    {
      MyClassptr=[COLOR=blue]this[/COLOR];
    }
    [COLOR=green]//main.cpp[/COLOR]
    [COLOR=blue]int[/COLOR] main()
    {
        MyClass MyNewClass;
        MyClassptr->Start();
        [COLOR=blue]return[/COLOR] 0;
    }
    
     
  2. ranjittechie

    ranjittechie New Member

    Joined:
    Jul 8, 2008
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    First of all you have to define the Start() and Stop() functions.Otherwise it will take MyClass as abstract class.

    After Definining these fucntions i run this same code it works fine

    so try it again it works
    For further queries kindly revert back
     

Share This Page