mardi 21 juin 2016

Why doesn't linking preserve encapsulation? Is it used in practice?


Lets assume the following header foo.h:

class Foo {
  private:
    void print() const;
};

and following foo.cpp:

#include <iostream>

#include "foo.h"

void Foo::print() const {
    std::cout << "Secret" << std::endl;
}

another header foo1.h, that is the same as foo.h unless method print is declared public:

class Foo {
  public:
    void print() const;
};

and this will be main.cpp, that just call print in foo1.h:

#include "foo1.h"

int main() {
    Foo f;
    f.print();
    return 0;
}

What seems strange for me is that the following linking gonna work:

g++ foo.cpp -c -o foo.o
g++ main.cpp -c -o main.o
g++ main.o foo.o -o exec
./exec

The last command will output:

Secret

So without knowing the concrete implementation of class Foo but, knowing its declaration and having its object file, we can create situation when its methods can be used even though they are declared private.

My questions are:

  1. Why does it work? Linker doesn't consider private and public declarations?

  2. Is this behavior useful in practice? If yes, how is it used? My guess that it could be useful for testing.


Aucun commentaire:

Enregistrer un commentaire