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,3553 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,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
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.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.
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?
- Fix the
error: cannot call member function without object
in C++ - Use an Instance of the Class to Access the Member Functions
- Use Static Member Functions
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.
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 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
Mesteriis 599 / 237 / 69 Регистрация: 08.08.2015 Сообщений: 1,637 |
||||||||||||||||
1 |
||||||||||||||||
20.01.2017, 22:07. Показов 11261. Ответов 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 |