Ошибка 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,3553 gold badges39 silver badges48 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,3425 gold badges31 silver badges40 bronze badges

answered Jul 14, 2009 at 20:19

sth's user avatar

sthsth

221k53 gold badges281 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,7372 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 badges15 silver badges30 bronze badges

answered Jul 14, 2009 at 20:21

dimba's user avatar

dimbadimba

26.6k34 gold badges140 silver badges196 bronze badges

Trusted answers to developer questions

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

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.
Автор Тема: ошибка: cannot call member function without object  (Прочитано 6851 раз)
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);


Записан

Mesteriis

599 / 237 / 69

Регистрация: 08.08.2015

Сообщений: 1,637

1

20.01.2017, 22:07. Показов 11261. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Доброе время суток ребят такая фигня, решил значит наконец то классы освоить но прям беда! чой то не пойму

h файл

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef MCT_H
#define MCT_H
#include <string>
 
class MCT
{
private:
 
    static std::string FirstString;
    static std::string SeacondString;
 
public:
 
    MCT();
 
    void PrintFS ();
    void PrintSS ();
    bool AddFS(std::string InputString);
    bool AddSS(std::string InputString);
};
 
#endif // MCT_H

реализация класса

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "mct.h"
 
MCT::MCT()
{
 
}
 
 
MCT::PrintFS ()
{
    if (FirstString.size()==0) std::cout << "FirstString is NULLn";
    std::cout<< FirstString << std::endl;
}
 
MCT::PrintSS ()
{
    if (FirstString.size()==0) std::cout << "FirstString is NULLn";
    std::cout<< FirstString << std::endl;
}
 
MCT::AddFS(std::string InputString)
{
    FirstString=InputString;
//    if (FirstString==InputString) return false;
    return true;
}
 
MCT::AddSS(std::string InputString)
{
    SeacondString=InputString;
//    if (SeacondString==InputString) return false;
    return true;
}

ну и маин файл

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
 
#include "mct.h"
 
using namespace std;
 
int main()
{
    new MCT;
 
    MCT::AddFS("test 1");
    MCT::AddSS("test 2");
 
    MCT::PrintFS();
    MCT::PrintSS();
 
 
    return 0;
}

и собственно ошибка

Bash
1
2
3
C:UsersAlexanderDocumentsjson_stringmain.cpp:21: ошибка: cannot call member function 'bool MCT::AddFS(std::string)' without object
     MCT::AddFS("test 1");
                        ^



0



GbaLog-

Любитель чаепитий

3737 / 1796 / 563

Регистрация: 24.08.2014

Сообщений: 6,015

Записей в блоге: 1

20.01.2017, 22:28

2

Лучший ответ Сообщение было отмечено Mesteriis как решение

Решение

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
 
#include "mct.h"
 
using namespace std;
 
int main()
{
    MCT* mct = new MCT;
 
    mct->AddFS("test 1");
    mct->AddSS("test 2");
 
    mct->PrintFS();
    mct->PrintSS();
 
 
    return 0;
}



1



599 / 237 / 69

Регистрация: 08.08.2015

Сообщений: 1,637

20.01.2017, 22:32

 [ТС]

3

GbaLog-, А можешь в двух словах объяснить?



0



Любитель чаепитий

3737 / 1796 / 563

Регистрация: 24.08.2014

Сообщений: 6,015

Записей в блоге: 1

20.01.2017, 22:39

4

Цитата
Сообщение от Mesteriis
Посмотреть сообщение

А можешь в двух словах объяснить?

Если метод класса не статический, то для обращения к ним нужен экземпляр этого класса.



0



  • Ошибка canary destiny 2
  • Ошибка can шины форд фокус 2 рестайлинг
  • Ошибка can сообщения ebc1 таймаут сообщения шины can камаз
  • Ошибка can сообщения dm1spn3 камаз
  • Ошибка can сообщения dm1spn2 ошибка шины can