0

I have been trying testing if multiple definition of a friend class in different .cpp files would work. To do that I defined a main class inside main_class.hpp file:

class main_class
{
private:
    int a;
    int b;

    int gimme_a()
    {
        return a;
    }

public:
    main_class(int a, int b) : a(a), b(b) {}

    int gimme_b()
    {
        return b;
    }

friend class main_class_friend;
};

Then I defined main_class_friend two times, firstly within main_friend_class1.cpp file:

class main_class_friend
{
    main_class c;
public:

    main_class_friend() : c(10, 10) {}

    int gimme_a()
    {
        return c.gimme_a();
    }

    int gimme_b()
    {
        return c.gimme_b();
    }
};

and a corresponding public test function:

void test1()
{
    main_class_friend ff;
    std::cout << "Gimme a: " << ff.gimme_a() << " and gimme b: " <<
        ff.gimme_b() << std::endl;
}

and then I defined the second main_class_friend within main_friend_class2.cpp and a corresponding public test function:

class main_class_friend
{
private:
    main_class ca;
    int c;
public:

    main_class_friend() : ca(9 ,9), c(11) {}

    int gimme_a()
    {
        return ca.gimme_a();
    }

    int gimme_b()
    {
        return ca.gimme_b();
    }

    int gimme_c()
    {
        return c;
    }
};


void test2()
{
    main_class_friend ff;
    std::cout << "Gimme a: " << ff.gimme_a() << " and gimme b: " << ff.gimme_b() 
        << " and gimme c: " << ff.gimme_c() << std::endl;
}

Finally I called test1 and test2 function inside main:

int main()
{
    test1();
    test2();
    return 0;
}

compiled the program (no errors from g++), and run it. The output was:

Gimme a: 9 and gimme b: 9
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)

What's really weird for me is that a and b were initialized by the constructor inside main_friend_class2.cpp and not the one from main_friend_class1.cpp where test1 function is defined.

Then I found that stack smashing can be easily debugged when a program is compiled with -fstack-protector flag. So I compiled it once again and the output from the program was then:

Gimme a: 9 and gimme b: 9
Gimme a: 9 and gimme b: 9 and gimme c: 11

so no more stack smashing problems, but both test1 and test2 functions use constructor from main_friend_class2.cpp file.

What's going on around here? I don't get it. Why there is a stack smashing error if there is no buffer overflow, because there isn't any buffer used?

My second question is: is there a way to define multiple times main_class_friend, but to use them in different files to make them "private" for the file inside which the class is used?

K. Koovalsky
  • 596
  • 4
  • 17

0 Answers0