Search code examples
c++classsyntaxc++20keyword

Compiler error in the statement "a->friend = b;"


unable to assign a shared pointer of a class to another shared pointer which is a member of the same class . expected unqualified-id before ‘friend’

#include <iostream>
#include <memory>
#include <iomanip>

class foo {
    double num;
    int age;
    public :
        void info() {
            std::cout << num << " " << age << std::endl;
        }
        std::shared_ptr<foo> friend;
        foo() = delete;
        foo(double num_param, int age_param) 
            : num(num_param), age(age_param) {
                std::cout << num <<  " : constructed\n";  
            }  
        ~foo() {
            std::cout << num <<  " : destroyed\n" ;
        }
};

int main() {
    std::shared_ptr<foo> a{new foo(5.3, 56)};
    std::shared_ptr<foo> b{new foo(11.6, 89)};
    a->info();
    b->info();
    a->friend = b; //not working
    b->friend = a; //not working
    a->info();
    b->info();
    
    return 0;
}

why I am getting "expected unqualified-id before ‘friend’". compiler g++-12


Solution

  • As Weijun Zhou, commented "friend" is a keyword and it shouldn't be used as a identifier. code worked after changing the shared pointer name.