Ошибка cannot call member function without object

This program has the user input name/age pairs and then outputs them, using a class.
Here is the code.

#include "std_lib_facilities.h"

class Name_pairs
{
public:
       bool test();
       void read_names();
       void read_ages();
       void print();
private:
        vector<string>names;
        vector<double>ages;
        string name;
        double age;
};

void Name_pairs::read_names()
{
     cout << "Enter name: ";
     cin >> name;
     names.push_back(name);
     cout << endl;
}

void Name_pairs::read_ages()
{
     cout << "Enter corresponding age: ";
     cin >> age;
     ages.push_back(age);
     cout << endl;
}

void Name_pairs::print()
{
     for(int i = 0; i < names.size() && i < ages.size(); ++i)
             cout << names[i] << " , " << ages[i] << endl;
}

bool Name_pairs::test()
{
   int i = 0;
   if(ages[i] == 0 || names[i] == "0") return false;
   else{
        ++i;
        return true;}
}


int main()
{
    cout << "Enter names and ages. Use 0 to cancel.\n";
    while(Name_pairs::test())
    {
     Name_pairs::read_names();
     Name_pairs::read_ages();
     }
     Name_pairs::print();
     keep_window_open();
}

However, in int main() when I’m trying to call the functions I get "cannot call 'whatever name is' function without object." I’m guessing this is because it’s looking for something like variable.test or variable.read_names. How should I go about fixing this?

Ziezi's user avatar

Ziezi

6,3753 gold badges39 silver badges49 bronze badges

asked Jul 14, 2009 at 20:15

trikker's user avatar

3

You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can’t just be used on their own. The main() function could, for example, look like this:

int main()
{
   Name_pairs np;
   cout << "Enter names and ages. Use 0 to cancel.\n";
   while(np.test())
   {
      np.read_names();
      np.read_ages();
   }
   np.print();
   keep_window_open();
}

Jason Plank's user avatar

Jason Plank

2,3365 gold badges31 silver badges40 bronze badges

answered Jul 14, 2009 at 20:19

sth's user avatar

sthsth

223k53 gold badges283 silver badges367 bronze badges

0

If you want to call them like that, you should declare them static.

answered Jul 14, 2009 at 20:20

Rob K's user avatar

Rob KRob K

8,7652 gold badges32 silver badges36 bronze badges

2

just add static keyword at the starting of the function return type..
and then you can access the member function of the class without object:)
for ex:

static void Name_pairs::read_names()
{
   cout << "Enter name: ";
   cin >> name;
   names.push_back(name);
   cout << endl;
}

answered Jun 4, 2019 at 9:57

Ketan Vishwakarma's user avatar

You are right — you declared a new use defined type (Name_pairs) and you need variable of that type to use it.

The code should go like this:

Name_pairs np;
np.read_names()

O'Neil's user avatar

O’Neil

3,7904 gold badges16 silver badges30 bronze badges

answered Jul 14, 2009 at 20:21

dimba's user avatar

dimbadimba

26.7k34 gold badges141 silver badges197 bronze badges

Trusted answers to developer questions

Grokking the Behavioral Interview

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

The “cannot call member function without object” error is a common C++ error that occurs while working with classes and objects. The error is thrown when one tries to access the functions of a class without instantiating it.

svg viewer

Code

Consider the following C++ code snippets that depict the code with the error scenario and the correct code. The solution is to create an object of a class (instantiation) before using its methods.

#include <iostream>

using namespace std;

class Employee

{

public:

string name = "John";

int age = 25;

void printData()

{

cout << "Employee Name: " << name << endl;

cout << "Employee Age: " << age << endl;

}

};

int main()

{

Employee::printData();

return 0;

}

RELATED TAGS

member function

object

error

without

c++

Copyright ©2023 Educative, Inc. All rights reserved

Learn in-demand tech skills in half the time

Copyright ©2023 Educative, Inc. All rights reserved.

soc2

Did you find this helpful?

  1. Fix the error: cannot call member function without object in C++
  2. Use an Instance of the Class to Access the Member Functions
  3. Use Static Member Functions

Error: Cannot Call Member Function Without Object in C++

This article describes the commonly occurring error cannot call member function without object while doing object-oriented programming using C++. Furthermore, it also provides potential fixes to the error.

Fix the error: cannot call member function without object in C++

A common error in C++ frequently occurs when working in object-oriented programming, stating cannot call member function without object. The cause of this error is that you are calling some member method of the class without instantiating the class.

Every class has a set of data members and some member functions. We need to create the class object to access the member methods or functions and then call/access the methods using this object.

Consider the following code.

#include<iostream>
using namespace std;
class Rectangle{
    private:
        int length=5;
        int width=8;
    public:
    double getArea()
    {
        return length*width;

    }
};
int main()
{
    cout<<"Area: "<<Rectangle::getArea()<<endl;
}

This code will generate the following output.

cannot call member function without object

Line #16 in the above code snippet tries to call the getArea() method using the class name. All the non-static members of a class must only be accessed through an object of the class; therefore, the line generates the error.

Use an Instance of the Class to Access the Member Functions

The error can be solved by calling the function/method with an object of the class like this:

int main()
{
    Rectangle r;
    cout<<"Area: "<<r.getArea()<<endl;
 }

This will give the correct output.

Use Static Member Functions

Static member functions are the functions of a class that do not need an object to call them. They can be called directly with the class name using the scope resolution operator ::.

Certain limitations must be kept in mind when using the static member functions. A static member function can access only the static data members of the class and can only call the other static member functions.

Let’s look at the example below discussing the solution to the cannot call member function without object error.

#include <iostream>

using namespace std;

class Rectangle{
    private:
        int length =5;
        int width=8;
    public:
    double getArea()
    {
        return length*width;
    }
    static void getShapeName()
    {
        cout<<"Hello, I am a Rectangle."<<endl;
    }

};
int main()
{

    Rectangle r ;
    cout<<"Area: "<<r.getArea()<<endl;
    Rectangle::getShapeName();
 }

This will give the following output.

Area: 40
Hello, I am a Rectangle.

The programming language is a bundle of different concepts, built-in functions, and operations; it also comes up with many errors. These errors can be of a logical type, syntax errors, and others as well. You can get many errors while coding when you make some logical or syntax errors in the code. One of the errors from many of these exceptions is “cannot call member function without object”. It occurs when we try to call a function in our program without making a class object. So, this guide contains examples to make this error happen and the solution to resolve it. Make sure you have been working on the Ubuntu 20.04 system and launch the terminal via “Ctrl+Alt+T”. Let’s begin with the examples.

Example 01:

Let’s begin our first example to elaborate on how we get the error “cannot call member function without object” in C++ code. So, the first thing we need to do is to create a c++ file. This file can be created with some text editor within the file explorer or within the shell. You can try opening it with the vim editor, text editor, or some other editor like GNU Nano editor. So, we have been directly opening this newly created file in GNU Nano editor using the “nano” command. Now, the empty newly created file is launched in the Nano editor and ready to be used.

We have been starting our code with the addition of some header files, i.e., “iostream”. You can use the “std” namespace in the code while declaring it before the main function. Otherwise, you have to use the keyword “std” with every cout and cin clause in the program. So, we have initialized it before the main method using the “using” keyword. We have created a simple class named “A” in the code. This class contains a single user-defined function named “show()”. The function contains the declaration of a character type variable named “a”. The first cout statement of this function asks for a character to be added by a user. The “cin” clause allows a user to add that character on the shell and save it to the variable “a”. The last cout statement has been used here to display the character on the shell that the user has input.

Now the class has ended, and we have started the main method. It’s time to call the function to execute it without using anything else. So, we have simply used the class name “A” with “::” to call the function “show()” in the main method. The main method is closed here. We are ready to save this code with Ctrl+S as it is already complete.

Get back to the terminal by using “Ctrl+X. Now, it’s high time to compile the code with the c++ built-in compiler of Ubuntu 20.04. Thus, we have used the “g++” compiler instruction here to simply compile the code file and see whether it is error-free or not. On compilation, it shows the error. This means we cannot just execute or call the function show() of class “A” without creating an object of this class.

So, we need to update the code file once again. Make use of the nano editor once again and resolve this error. So the old file is opened again. We need to only change the main() function to elude this error so far. So, we have created an object “obj” of class “A”. Now, this object “obj” has been used here to call the function show() of the class “A” using the “dot” between the object name and function name. Save the code to reflect the changes on execution using the simple shortcut key, i.e., “Ctrl+S”. The updated code has been displayed in the image below. Let’s come back to the terminal to compile the updated code using “Ctrl+X”.

Used the “g++” compiler instruction for the purpose of code compilation. We have got no error this time. On execution of the code, we have got the result shown below. It asked to enter the character, adding “A”. In return, it displayed the character on the shell. Using the object to call the function show().

Example 02:

Let’s have another example of getting the same error and solving it afterward. So, we opened the file error.cc and created the below-shown code. This code has been started from the iostream header file, std namespace, and ended on the main method. Our program contains two classes, A and B. A is parent class, and B is child class of A inheriting its properties here. Parent class A contains a function “print()” having a single statement displaying that this is a parent class function. The child class contains a function “show()” with a cout statement displaying that the child class method has been executed. The main() function contains a simple “::” method to call both the methods using their respective classes, i.e., “A” and “B”. Let’s just run this code to see how it works.

When we compiled the code, we got the exception error saying “cannot call member function without object” for both the function calls. This is because we did not create the objects to call the functions of respective classes and did it directly.

Let’s just open the file once again using the “nano editor”. There is no need to change the whole code; only the main() method requires a little modification. As you can have a look that, we have created an object obj1 of parent class “A” and used it to do a function call to print() method. Then, we created an object “obj2” of child class B and did a function call to function “show()” here to execute it. We can also avoid making the parent class object “obj1” and still call its function by using the child class object “obj2”. Both the functions in parent and child classes have different names, so it will not cause any error. Let’s just save the code file with Ctrl+S and come back to the terminal to see if the error is resolved or not.

After the compilation of updated code, we can have a glance that the error “cannot call member function without its object” has been removed finally, and the code is ready to be executed. Both parent and child class functions were executed as shown upon running the code.

Conclusion:

This article contains a simple demonstration of creating an error “cannot call member function without the object” in the c++ program. We have used the concept of classes here to make it possible. Then, we have also demonstrated the solution to resolve this error within the examples. We are quite hopeful that this article will be helpful to all the c++ naïve users.

About the author

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Автор Тема: ошибка: cannot call member function without object  (Прочитано 7075 раз)
megido

Гость


значит есть у меня вот такая функция

шапка:
static void CALLBACK ProcessBuffer(const void *buffer, DWORD length, void *user);
код:
void  Player::ProcessBuffer(const void *buffer,DWORD length,void *user)
{
    emit SetSongName(time_info);

}
vold Player::Play()
{
    chan = BASS_StreamCreateURL(url,0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,ProcessBuffer,this);

 }

когда я пытаюсь в ней послать сигнал получаю вот эту ошибку

ошибка: cannot call member function ‘void Player::SetSongName(QString)’ without object
     emit SetSongName(time_info);

кстати вызвать из нее другую функцию я тоже не могу

какой объект оно хочет?

« Последнее редактирование: Июнь 19, 2016, 02:12 от megido »
Записан
Bepec

Гость


Без кода можем только анекдот рассказать, за денежку.


Записан
Racheengel

Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2679

Я работал с дискетам 5.25 :(

Просмотр профиля


а SetSongName помечена как Q_SIGNAL?


Записан

What is the 11 in the C++11? It’s the number of feet they glued to C++ trying to obtain a better octopus.

COVID не волк, в лес не уйдёт

kambala


из статического метода сигнал ты не пошлешь, так как это метод на уровне класса, не конкретного объекта.

тебе надо в качестве дополнительного параметра этому коллбэку передавать this (параметр user, насколько я понимаю), потом в коллбэке кастануть user к классу Player и вызвать метод (его надо написать), который внутри и пошлет сигнал.

« Последнее редактирование: Июнь 19, 2016, 02:29 от kambala »
Записан

Изучением C++ вымощена дорога в Qt.

UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher

megido

Гость


а SetSongName помечена как Q_SIGNAL?

а как же


Записан
megido

Гость


из статического метода сигнал ты не пошлешь, так как это метод на уровне класса, не конкретного объекта.

тебе надо в качестве дополнительного параметра этому коллбэку передавать this (параметр user, насколько я понимаю), потом в коллбэке кастануть user к классу Player и вызвать метод (его надо написать), который внутри и пошлет сигнал.

спасибо за наводку. работает

    Player* pthis = (Player*)user;
    pthis->SetTimeInfo(time_info);


Записан

Понравилась статья? Поделить с друзьями:
  • Ошибка c90d60 bmw
  • Ошибка can t create output file
  • Ошибка c7990 kyocera как сбросить
  • Ошибка c9040 на kyocera taskalfa
  • Ошибка can not choose method маркет кс го