Derived class problem! Help

Hi, i have a problem with derived class. I can't understand why this code doesn't work:

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
43
44
45
46
47
48
49
50
  class point
 {
      public:
        point();
        point(double x, double y);
        //functions

      protected:
        double x;
        double y;
 };

  class vertex : public point 
  {
       public:
        vertex();
        vertex(double, double, int, double, double);
        double f(point, int);

       private:
        int k;
        double kx, ky;
  };

//vertex.cpp

#include "vertex.h"
#include "point.h"
#include <cmath>

#include <iostream>
using namespace std;

vertex::vertex()
{
}

vertex::vertex(double x, double y, int index, double a, double b):point(x, y)
{
    k=index;
    kx=a;
    ky=b;
}

double vertex::f(point p, int e)
{
    return ((kx*p.x + ky*p.y)+e*0);
}



Does anyone can tell me the error??
I think I've misunderstood the protected keyword...
Last edited on
What's not working? You haven't said.
Compile error? Linker error? Run time trap? Wrong results?

Line 18: Your comment says "implemented in .cpp file", but lines 18-21 are an implementation also. This could cause a duplicate procedure error in the linker if this code were to compile. As it's coded here, it won't compile. p and e are not defined. If it's truely implemented in the .cpp file, remove lines 19-21 and put a ; on line 18.



I've modified the code, i hope that now you can understand my problem.

There' a compile error that says "error: 'double point::x' is protected"

The problem is that I want to use in the "f" function of the derived class vertex the "x" and "y" of the point p declared as protected variables in the base class point, and I don't understand why I can't do it like this...

I hope I've been more clear now...thank you anyway!
It would have been helpful if you had identified the exact line containing the error.

vertex inherits from point, but that doesn't mean that it can access some other p's protected members. p is a different instance. protected means that a vertex instance can access it's own x and y, not some other instance of Point.
Sorry, the error was in line 47.

Anyway, I think I've understood the problem.
One last question: if i make the vertex class friend of the point class, the problem is solved...isn't it??

If so, is "normal" to make a derived class friend of his base class to solve situations like this?? Because I'm starting to understand c++ and I'm not sure that this woud be a correct solution!
Yes, that will work. There are examples here:
http://www.cplusplus.com/doc/tutorial/inheritance/

The other approach is to provide getter functions in Point.
Topic archived. No new replies allowed.