How to use references and pointers in c++ classes? - class

i have the following problem: I am using an existing class which creates an object called server_t.
Another function expects *server_t as an argument.
I wanted to shrink the code and added a class which has following members:
#ifndef _PMCLASS
#define _PMCLASS
#include "pmlib.h"
class pmServer{
private:
server_t server ;
counter_t counter;
line_t lines;
server_t * server2;
int set, frequency, aggregate ;
public:
pmServer();
pmServer(int set, int frequency, int aggregate);
~pmServer();
void setSet(int s);
void setFrequency(int f);
void setAggregate(int a);
int getSet(void);
int getFrequency(void);
int getAggregate(void);
server_t* getServerT(void);
counter_t* getCounterT(void);
line_t* getLineT(void);
server_t* getZeiger(void);
};
#endif
then i created the constructors:
#include "pmClass.h"
#include <iostream>
using namespace std;
void pmServer::setSet(int s){
this->set = s;
}
void pmServer::setFrequency(int f){
this->frequency = f;
}
void pmServer::setAggregate(int a){
this->aggregate = a;
}
int pmServer::getSet(void){
return set;
}
int pmServer::getFrequency(void){
return frequency;
}
int pmServer::getAggregate(void){
return aggregate;
}
server_t* pmServer::getPointer(){
return &server;
}
pmServer::pmServer(){
set = -1;
frequency = 0;
aggregate = 1;
}
then i tried to create an object ->worked, but then i wanted to use the pm_set_server(...)
it wants following arguments: int pm_set_server( char *ip, int port, server_t *pm_server)
void run() {
build_initial_mesh();
// Construct / read in the initial mesh.
pmServer server1;
pm_set_server("xxx.xxx.xxx.xxx", 6526,server1.getPointer); //its a correct ip address , no panic :)
i got that:
error: argument of type 'server_t*' (pmServer::)() does not match 'server_t*'
but this worked without any problems:
void run() {
// Construct / read in the initial mesh.
//pmServer server1;
server_t test;
pm_set_server("xxx.xxx.xxx.xxx", 6526,&test);
build_initial_mesh();
The thing is, i didn't want to create everytime new ojects and wanted to do that in the constructor...Does somebody have any idea?
thanks.
greetings Thomas

In C++, function calls need brackets*:
pm_set_server("xxx.xxx.xxx.xxx", 6526,server1.getPointer());
*exceptions apply, for operators.

Related

Segmentation fault in header file

I have defined a Parent.h file, having Parent class with following data members:-
#pragma once
#include <string>
using namespace std;
class Person
{
private:
string id;
string name;
string email;
int contact_number;
string address;
public:
Person();
~Person();
void set_id(string);
void set_name(string);
void set_email(string);
void set_contact_number(int);
void set_address(string);
string get_id();
string get_name();
string get_email();
int get_contact_number();
string get_address();
};
Person::Person()
{
this->id = "";
this->name = "";
this->email = "";
this->contact_number = 0;
this->address = "";
}
void Person::set_id(string id)
{
this->id =id;
}
I have defined the rest of the functions(setters and getters) likewise in Parent.h file.
After that I am making a child class in Student.h header file, this Student class will publicly inherit the Parent class
#pragma once
#include"Courses.h" //course is aggregating to a student
#include"AcademicRecord.h"
#include "Person.h"
#include "Department.h"
#include<string>
#include<vector>
using namespace std;
class Student:public Person,public AcademicRecord,public Department
{
private:
string institute_email;
public:
Courses A;//A contains all information about the courses a student has opt for.
Student();
~Student();
//Using polymorphism between methods
void ShowStudentAcademicRecord(); //shows the academic record of current student
void ShowStudentCoursesInfo(); //getting the information for all courses of student
//setter
void set_institute_email(string email);
void setDepartmentID(string);
//getter
string get_institute_email();
};
After that I have a Display.h file having vector of Students as its Data member and using a member function in Display, I am asking user to input data members like ID,Name,Address,... for individual students.
#include "Student.h"
using namespace std;
class Display
{
public:
vector<Student> students;
Display();//default constructor
//setter
void setStudentData();
};
void Display::setStudentData()
{
int size;
cout<<"Enter the number of students: ";
cin>>size;
Student *current; //current Student
for (int i = 0; i < size; i++)
{
current = &students[i];
cout<<"For student "<<i+1<<"\nEnter the following: \n";//For general details
cout<<"ID Name Email Contact_Number Address Institute_Email\n";
string ID,Name,EMail,Address,insti_email;
int contact_number;
cin>>ID>>Name>>EMail>>contact_number>>Address>>insti_email;
current->set_id(ID);
current->set_name(Name);
current->set_email(EMail);
current->set_contact_number(contact_number);
current->set_address(Address);
current->set_institute_email(insti_email);
}
And when I try inserting value insides students by executing main.cpp file.
I get segmentation fault at run-time inside Person class at setter function, where the first setter I have declared inside the class is void set_id(string).
#include "Display.h"
#include<vector>
#include<string>
int main()
{
Display display;
display.setStudentData();
}
Error:-
I tried:-
1.Rechecking the setter function for any error
2.Bring all the classes inside the main.cpp file,instead of header files, but still the error continues.
I expected the program to take the desired input for various data members of student elments of vector students inside Display class.
Instead I got a seg-fault.
Please if anyone can tell me what I have done wrong, or do I have to do malloc somewhere, inside a function?
As Nate Eldredge, has said I should use push_back instead of accessing ith element of students vector in setStudentData() function, as initially during default declaration of a Display class, the students vector is empty. Hence trying to access students[i] in current = &students[i], I am getting segmentation fault.
The appropriate code for Display.h should be then
#include "Student.h"
using namespace std;
class Display
{
public:
vector<Student> students;
Display();//default constructor
//setter
void setStudentData();
};
void Display::setStudentData()
{
int size;
cout<<"Enter the number of students: ";
cin>>size;
total_students += size;
Student *temp =new Student(); //temp Student
for (int i = 0; i < size; i++)
{
cout<<"For student "<<i+1<<"\nEnter the following: \n";//For general details
cout<<"ID Name Email Contact_Number Address Faculty_Type Faculty_Description\n";
string ID,Name,EMail,Address,insti_email;
int contact_number;
cin>>ID>>Name>>EMail>>contact_number>>Address>>insti_email;
temp->set_id(ID);
temp->set_name(Name);
temp->set_email(EMail);
temp->set_contact_number(contact_number);
temp->set_address(Address);
temp->set_institute_email(insti_email);
cout<<"Enter the Course Details: \n";//For Course Details
int size_course;
cout<<"Enter the number of courses: ";
cin>>size_course;
cout<<"Enter the following for each course: \n";
cout<<"Course_Name Marks Attendance Percentage \n";
string name;
int marks;
float attendance;
for (int i = 0; i < size_course; i++)
{
cin>>name>>marks>>attendance;
temp->A.set_courses_enrolled(name);
temp->A.set_course_wise_marks(marks);
temp->A.set_coursewise_attendance_percentage(attendance);
}
cout<<"Enter the Academic Record Details: \n";//For Academic Record Details
string program_name; int admission_no, enroll_no, begin_year, end_year, credits; float CGPA;
cout<<"Enter Program_name, admission_no enroll_no begin_year end_year credits CGPA";
cin>>program_name>>admission_no>>enroll_no>>begin_year>>end_year>>credits>>CGPA;
setStudentAcademicRecord(temp,i,program_name,admission_no,enroll_no,begin_year,end_year,credits,CGPA); //passing temp pointer in this one
students.push_back(*temp); //adding a new student in students vector
}

Compile Errors in Class with User Defined Functions

I am trying to build a class that stores a user-defined function inside of it for later use. I have decided to use the boost::function object to do so.
However, I get the following error on compile:
error: no match for ‘operator=’ in ‘((SomeClass*)this)->SomeClass::someFunction = ((SomeClass*)this)->SomeClass::DefaultFunction’
I do not understand this error, since someFunction and DefaultFunction should, as far as I can see, have the same types.
The code is shown below:
#include <boost/function.hpp>
class SomeClass{
private:
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
public:
SomeClass();
~SomeClass();
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=DefaultFunction;
}
~SomeClass::SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
void MyProgram(){
SomeClass s;
}
Can anyone offer any pointers as to how to construct such an object? Alternatively, iff there is a better way than the one I am attempting, could you explain it to me?
Kindest regards!
DefaultFunction is a member function of SomeClass.
Member function is called for some instance of SomeClass.
This function takes "hidden" pointer to SomeClass instance as its first parameter addition to int.
So member function is not the same as free function.
Your someFunction is object of boost::function, so it is wrapper for callable object.
Your requirements to that object are: take int and returns int.
In order to assign DefaultFunction (as member function) to someFunction you need to create this callable object.
Here you need to specify for which instance of SomeClass this object will be called, to do that use boost::bind:
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, boost::placeholders::_1);
}
In the code above you create callable object which will behave as
struct unnamedClass {
SomeClass* sc;
unnamedClass (SomeClass* sc) : sc(sc) {} // here sc is this of SomeClass
int operator()(int arg)
{
return sc->DefaultFunction(arg);
}
};
so when you invoke someFunction(10) it takes 10 as argument and call DefaultFunction for current this instance.
This
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
works because f is free function, which takes no hidden - pointer to class instance.
Using the answer of #rafix07, the following code compiled:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/bind/placeholders.hpp>
class SomeClass{
private:
public:
SomeClass();
~SomeClass();
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, _1);
}
SomeClass::~SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
int MyOwnProgram(int i){
return i+2;
}
void MyProgram(){
SomeClass s;
std::cout<<s.someFunction(2)<<std::endl;
s.SetFunction(MyOwnProgram);
std::cout<<s.someFunction(2)<<std::endl;
}
int main()
{
MyProgram();
}
The output from the program is:
3
4

pthread to invoke member func by wrapping it externally

I'm trying to invoke a member function by pthread by using an external wrapper but it doesn't quite work for me, I get a seg fault. Why is this?
Here's a little test program that displays the problem:
#include <iostream>
#include <pthread.h>
class test {
public:
test();
~test();
void RunTh(void);
private:
pthread_t *pid;
};
void *Run_wrp(void *context);
void test::RunTh(void)
{
while(1);
}
test::test()
{
pthread_create(pid,NULL,&Run_wrp,this);
}
test::~test(){}
int main(void) {
test tmp;
std::cin.get();
}
void *Run_wrp(void *context)
{
((test*)context)->RunTh();
}
Your pid member variable is just a pointer, not an actual pthread_t object.
Change it to:
private:
pthread_t pid;
Then create the new thread with:
pthread_create(&pid,NULL,&Run_wrp,this);
Also, if you want to keep everything contained in the class, you can make your Run_wrp() function a static member function of test, as long as you keep the same signature (return value/arguments). It needs to be static, as non-static functions take the this pointer to the class as a hidden argument, and thus end up with a different signature than what you need for pthread_create().

A program using class template, pair, vector

I'm trying to program the following:
A template class map having a pointer to a vector that contains elements std::pair<T,Q>, where T and Q are template types. It's supposed to work similarly to std::map and T is 'key' type, whereas Q stands for 'value' type. Besides the following should be implemented:
1. Constructor & destructor.
2. Function empty returning bool (if the object is empty).
3. Function size (using count_if)
4. Function clear that deletes all vector records.
5. Operator [] which allows for: map["PI_value"] = 3.14; It should use function find
6. Operators =, ==, !=, >> (using equal function)
I've been trying to code the above task, but have stuck on the code below.
Do you have any ideas to repair this mess?
#include <iostream>
#include <tuple>
#include <utility>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T, typename Q>
class mapa
{
private:
vector<std::pair<T,Q>>* ptr;
public:
/**< DEFAULT CONSTRUCTOR/////////////////////////// */
mapa()
{
ptr = new vector<std::pair<T,Q>>;
ptr->push_back(std::pair<T,Q>(0,0));
}
/**< DESTRUCTOR////////////////////////////////////// */
~mapa(){ delete ptr;}
/**< EMPTY()////////////////////////////// */
bool empty()
{
if(ptr)
return false;
else
return true;
}
/**< SIZE()///////////////////////////////// */
int size()
{
return ptr->size();
}
/**< CLEAR()///////////////////////////////// */
void clear()
{
ptr->clear(ptr->begin(), ptr->end());
}
/**< OPERATOR[]/////////////////////////////////////////// */
vector<std::pair<T,Q>>* & operator[](T key)
{
auto ptr2 = ptr;
if(empty())
{
std::pair<T,Q> para;
para.first = key;
para.second = 0;
ptr2->push_back(para);
//ptr2->push_back(std::pair<T,Q>(key,0));
}
else
{
auto ptr2 = find_if( ptr->begin(), ptr->end(),
[](std::pair<T,Q> example,T key)
{
return(example.first==key);
}
);
}
return ptr2;
}
}; //class end
The lambda provided to std::find_if is declared wrong.
If you see e.g. this reference for std::find_if, you will see that the functions should be like
bool pred(const Type &a)
That means the lambda should be something like
[&key](const std:pair<T, Q>& element) { return element.first == key }
There are also other problems with your operator[] function, like that it should return Q& instead of a reference to the vector pointer. You should also remember that std::find_if returns an iterator to the found element, or end() if not found.

What are function typedefs / function-type aliases in Dart?

I have read the description, and I understand that it is a function-type alias.
A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.
http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#kix.yyd520hand9j
But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?
I think I need one or two real code examples.
A common usage pattern of typedef in Dart is defining a callback interface. For example:
typedef void LoggerOutputFunction(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Running the above sample yields the following output:
Hello World
2012-09-22 10:19:15.139: Hello World
The typedef line says that LoggerOutputFunction takes a String parameter and returns void.
timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.
Let me know if you need another example.
Dart 1.24 introduces a new typedef syntax to also support generic functions. The previous syntax is still supported.
typedef F = List<T> Function<T>(T);
For more details see https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md
Function types can also be specified inline
void foo<T, S>(T Function(int, S) aFunction) {...}
See also https://www.dartlang.org/guides/language/language-tour#typedefs
typedef LoggerOutputFunction = void Function(String msg);
this looks much more clear than previous version
Just slightly modified answer, according to the latest typedef syntax, The example could be updated to:
typedef LoggerOutputFunction = void Function(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Typedef in Dart is used to create a user-defined function (alias) for other application functions,
Syntax: typedef function_name (parameters);
With the help of a typedef, we can also assign a variable to a function.
Syntax:typedef variable_name = function_name;
After assigning the variable, if we have to invoke it then we go as:
Syntax: variable_name(parameters);
Example:
// Defining alias name
typedef MainFunction(int a, int b);
functionOne(int a, int b) {
print("This is FunctionOne");
print("$a and $b are lucky numbers !!");
}
functionTwo(int a, int b) {
print("This is FunctionTwo");
print("$a + $b is equal to ${a + b}.");
}
// Main Function
void main() {
// use alias
MainFunction number = functionOne;
number(1, 2);
number = functionTwo;
// Calling number
number(3, 4);
}
Output:
This is FunctionOne
1 and 2 are lucky numbers !!
This is FunctionTwo
3 + 4 is equal to 7
Since dart version 2.13 you can use typedef not only with functions but with every object you want.
Eg this code is now perfectly valid:
typedef IntList = List<int>;
IntList il = [1, 2, 3];
For more details see updated info:
https://dart.dev/guides/language/language-tour#typedefs
https://www.tutorialspoint.com/dart_programming/dart_programming_typedef.htm
typedef ManyOperation(int firstNo , int secondNo); //function signature
Add(int firstNo,int second){
print("Add result is ${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is ${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is ${firstNo/second}");
}
Calculator(int a,int b ,ManyOperation oper){
print("Inside calculator");
oper(a,b);
}
main(){
Calculator(5,5,Add);
Calculator(5,5,Subtract);
Calculator(5,5,Divide);
}