Ошибка 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,3453 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,7272 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.5k33 gold badges140 silver badges196 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?

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



  • Forum
  • Beginners
  • Cannot call member function without obje

Cannot call member function without object

Hi, I’m having problem calling a function from a class in the main.cpp. Could someone tell me how to fix this please?

1
2
3
4
5
6
7
8
9
10
11
12
//main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "CD.h"

using namespace std;
class CD;

double mind, maxd;
CD dwindow = CD::setd(mind, maxd);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//CD.h

#ifndef CD_H_
#define CD_H_

#include <string>
#include <vector>

using namespace std;

class CD {
public:
	virtual ~CD();
	CD(Data, double, double);

	/// Virtual copy constructor.
	virtual CD* clone() const = 0;

	void setd(double mind, double maxd);
};
#endif 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//CD.cpp

#include "iostream"
#include "CD.h"

using namespace std;

//method: set min and max d's
void CD::setd(double mind, double maxd) {
	_mind = mind;
	_maxd = maxd;
}
CD::~CD() {
}

If I set the method to be static, then I get the following error: «cannot declare member function ‘static void CD::setd(double, double)’ to have static linkage».
Thank you in advance for your help!

A class represents a «thing», but the class itself is not actually a thing. You need to create objects of that class. Each object is its own thing.

For example… string is a class. This means that you can have multiple «objects» of type string. Each has its own string data.

1
2
string foo = "hi";
string bar = "there";

Here, foo and bar are both strings. Now you can call member functions (such as the length function) by using the object name and the dot operator:

 
size_t len = foo.length();  // get the length of the foo string 

But without an object, a call to length makes no sense:

1
2
3
4
size_t len = string::length();  // ??  what string are we getting the length of?
  //  is it foo?  is it bar?  is it something else?
  // doesn't make any sense!
  //  so the compiler will give this line an error. 

This is basically what you’re doing. You’re trying to call setd, but you’re not telling the compiler which CD object you want to set. So it spits that error at you.

You’ll need to create an object:

1
2
3
CD myCD;

myCD.setd( ... );

Last edited on

where do I create that object?

Objects are just like normal variables (like ints, doubles, etc). Declare it wherever you need to use it.

Topic archived. No new replies allowed.

Понравилась статья? Поделить с друзьями:
  • Ошибка cannot be applied to given types
  • Ошибка cannot find sims 3 root
  • Ошибка cannot access nls data
  • Ошибка cannot find project or library
  • Ошибка canceling statement due to user request