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
6,3453 gold badges39 silver badges48 bronze badges
asked Jul 14, 2009 at 20:15
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
2,3425 gold badges31 silver badges40 bronze badges
answered Jul 14, 2009 at 20:19
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 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
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
3,7904 gold badges15 silver badges30 bronze badges
answered Jul 14, 2009 at 20:21
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.
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.
Did you find this helpful?
|
Автор | Тема: ошибка: cannot call member function without object (Прочитано 6819 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
Mesteriis 599 / 237 / 69 Регистрация: 08.08.2015 Сообщений: 1,637 |
||||||||||||||||
1 |
||||||||||||||||
20.01.2017, 22:07. Показов 11232. Ответов 3 Метки нет (Все метки)
Доброе время суток ребят такая фигня, решил значит наконец то классы освоить но прям беда! чой то не пойму h файл
реализация класса
ну и маин файл
и собственно ошибка
0 |
GbaLog- Любитель чаепитий 3737 / 1796 / 563 Регистрация: 24.08.2014 Сообщений: 6,015 Записей в блоге: 1 |
||||
20.01.2017, 22:28 |
2 |
|||
Решение
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 |
А можешь в двух словах объяснить? Если метод класса не статический, то для обращения к ним нужен экземпляр этого класса.
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?
|
|
|
|
|
|
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.
|
|
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:
|
|
But without an object, a call to length makes no sense:
|
|
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:
|
|
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.