virtual function = 0

Apr 7, 2011 at 2:00pm
Hi everybody

i have a question. Why is in this code

1
2
3
4
5
6
7
class Body {
  public:
    virtual double Volume() = 0 {
    }
    virtual double Surface() = 0 {
    }
}


equating to zero?

Thanks
Apr 7, 2011 at 2:36pm
It is called pure virtual or abstract function and requires to be overwritten in an derived class.
Apr 7, 2011 at 3:05pm
The syntax above is wrong, To have pure virtual functions you should have this:
1
2
3
4
5
class Body {
  public:
    virtual double Volume() = 0;
    virtual double Surface() = 0;
};
( No function bodies )
Apr 7, 2011 at 3:56pm
But it translates VS2011 without errors...
So, everywhere, when i can use virtual/abstract function i must get the equating to zero, why is that? What be done, when i won't use this equating? I mean just use

virtual type Function();

without function bodies and the equating to zero
Apr 7, 2011 at 4:02pm
A pure virtual function makes its class abstract, because it cannot be instantiated.
Apr 7, 2011 at 4:26pm
To finchCZ
You need to learn up on Classes and polymorphism
Apr 7, 2011 at 4:33pm
yes i know, so i asked a question, because i want to learn it

thanks for help anyway
Apr 7, 2011 at 4:57pm
FYI everyone, you CAN give a pure virtual function a definition, it just won't be used.

http://www.parashift.com/c++-faq-lite/abcs.html#faq-22.4
Apr 7, 2011 at 5:09pm
Not sure if I understood that, so you can make a function purely virtual which prevents the instantiation of the base class, but you can still call it from a derived class or what? Otherwise I wouldn't see any point in providing a definition for an abstract function.
Apr 7, 2011 at 5:10pm
You can still call it though.
Apr 7, 2011 at 5:19pm
If you give a definition, you cannot instantiate the class, as per a normal pure virtual function. Basically all it does is let you possibly define some common functionality that derived classes might want.
Apr 7, 2011 at 5:48pm
This is what I mean (although I have not sen it in practice)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Base
{
public:
    virtual void VFuncA()=0;
    int x;

};

//Give the pure virtual function a body
void Base::VFuncA()
{
    x =3;

}

class Derived: public Base
{

public:
    void VFuncA()
    {

        Base::VFuncA();//calls bas class version

    }

};


int _tmain(int argc, _TCHAR* argv[])
{
    
     //Base *pb = new Base;//Error base class is abstract
    
    Base *pb = new Derived;
    
    pb->VFuncA();
    
   delete pb;

    return 0;
}
Topic archived. No new replies allowed.