Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ calling functions

I'm new to C++ and I have this problem that the compiler is throwing at me whenever I compile my program. From what I've learnt so far you have a class in which you declare constructors and functions. Then after the class you implement the functions. Then in the main you call/manipulate them. I was writing a linkedlist program but I kept getting this annoying compiler error:

error: request for member 'get_number' in 'test', which is of non-class type 'LinkList*'

My original program was quite longer than the below, but as I kept getting the above error I wrote a really simple program just to see where the error was being thrown. Despite writing it very simple I got the EXACT same error. So I'm doing something wrong when I'm calling the function that I have declared and implemented.

If someone could just help me point out what I'm doing wrong and why I can't call that function:

#include <iostream>
using namespace std;

class LinkList 
{
public:
    int result;

    //declaring the constructor
    LinkList(int i);

    //declaring simple function
    int get_number();
};

//Implementing the constructor
LinkList::LinkList(int i) 
{
    result = i; 
};

//implementing test function
int LinkList::get_number()
{
    return result;
}

int main()
{
    LinkList *test = new LinkList(5);

    int getting_number = 0;

    //Error trigger:
    test.get_number();

    cout<<getting_number;

    return 0;
}
like image 665
Force444 Avatar asked Mar 30 '26 22:03

Force444


2 Answers

Test is a pointer to a LinkList object, you have to access properties and members on test using the arrow operator (->), for example: test->get_number();

Or you could just not create a pointer to the object and create a normal object.

like image 180
Matthias Van Eeghem Avatar answered Apr 02 '26 03:04

Matthias Van Eeghem


just use

LinkedList test(5);

instead of

LinkList *test = new LinkList(5);

if you insist on using the new variant you need to change the

test.get_number();

to

test->get_number();

and free (delete) your test object before exiting the function;

and even then you are not assigning the return value from get_number to anything, so your getting_number varaible is still 0;

like image 37
Dampsquid Avatar answered Apr 02 '26 02:04

Dampsquid