Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Extern Break Encapsulation

Tags:

c++

c

oop

extern

qt

I am new to C++ and I am creating a game. I have a class called main in which I declare

Game * game; //globally
int main() {
    game = new Game();
    game->show();
}

My class game initiates my game etc. Now in other classes (player, enemy, etc.), I access variables from the game such as player health using

#include<game.h>
extern Game * game;
func::func() {
    game->health->resetHealth();
}

Is this breaking encapsulation/ood paradigm? Is it bad practice? The thing is I can see any other way of doing it for a game.

like image 229
hat_to_the_back Avatar asked Sep 14 '25 20:09

hat_to_the_back


1 Answers

Yes, extern breaks encapsulation. The main concept of encapsulation is data hiding and binding property and behavior of an object in a single entity. Making the variable extern would break the law.
In some more advance OOP language like java, there is no extern. And in Java, it always suggested making property/field private to restrict its access.

like image 200
Razib Avatar answered Sep 16 '25 11:09

Razib