Home > database >  C circular Class references philosophy
C circular Class references philosophy

Time:11-30

Imagine the next problem. I want a class Map. Every Map instances contains a list of Locations. I also want that every Location knows of the Map that owns him. (Could this hinder encapsulation?) In Python I can use type hints, with no problem. I can define both classes in either order.

from __future__ import annotations
class Map:
    def __init__(self):
        self.locations: list[Location]
        self.locations = []
class Location(self, ):
    def __init__(self, owner: Map):
        self.owner = owner

This hinders encapsulation, I guess. But in Python, aren't we all adults according to the philosophy of the language? This helps me a lot. If the Location child can access the parent, I can change something in the Location and the Parent can know.

Can I use this kind of design in C ? It this recommended? Can a child have a reference of his father? Can I declare a child class with knowledge of its parent AT THE SAME TIME that the parent know of its children?

I've learned C by myself and I never read about it.

CodePudding user response:

There is no problem with doing this in C . You just need to forward declare the location class.

As far as encapsulation goes, it isn't really an issue if Location is still using Map's public interface. If you want Location to not have to use Map's public interface Map could friend the location class but in that case encapsulation is being violated; it's a matter of taste though. There are no right or wrong answers about this kind of stuff.

Anyway code below:

#include <iostream>
#include <vector>

class Location;  // <= this is a forward declaration.

class Map {
private:
    std::vector<Location> locations_;
public:
    void insertLocation(float longitude, float lattitude);
};

class Location {
private:
    Map& parent_;
    float longitude_;
    float lattitude_;
public:
    Location(Map& map, float longi = 0.0f, float lat = 0.0f) :
        parent_(map), longitude_(longi), lattitude_(lat)
    {}
};

void Map::insertLocation(float longitude, float lattitude) {
    locations_.emplace_back(*this, longitude, lattitude);
}

int main(void) {
    Map map;
    map.insertLocation(10.0, 40.0);
    return 0;
}

CodePudding user response:

In C , the class declaration usually goes in the header, and the class methods go in the .cpp file. This is different from Python.

An important consequence is that you can include the parent header in the child .cpp file and vice versa. Hence, the child class methods can use the parent declaration and vice versa.

  •  Tags:  
  • c
  • Related