Calling function in C++ without creating an object - c++

I've read of similar problems to this, but the solutions provided didn't work for me so.
I want to call a function that exists in another class located in a different .cpp file. I don't want to create an instance of the object, I just want to use the function.
My code that tries to call the function:
switch (option)
{
case 1:
cout << "\nDoing stuff\n\n" ;
Controller::AlbumOps SayHey();
//SayHey should have run but isn't working
break;
And the function I'm trying to call:
#include "Menu.hpp"
#include "Album.hpp"
#include "stdio.h"
#include "AlbumOps.hpp"
#include <iostream>
using namespace std;
namespace Controller
{
static void Controller::AlbumOps::SayHey ()
{
cout << "Hey\n";
}
}
When I execute the code, the Hey is never printed. I thought the solution was to make the function static but that hasn't worked for me.

The call should be
Controller::AlbumOps::SayHey();
// ^^
// double-colon
You should put static on the in-class function declaration, not the out-of-class function definition (where it means something completely different, "internal linkage"). That is:
in the header (AlbumOps.hpp):
// ...
namespace Controller
{
class AlbumOps {
public:
// ...
static void SayHey(); // Note: 'static' here
};
}
// ...
and in the implementation file (AlbumOps.cpp): either:
// ...
void Controller::AlbumOps::SayHey() // Note: no 'static'
{
cout << "Hey\n";
}
// ...
or:
// ...
namespace Controller
{
// ...
void AlbumOps::SayHey() // Note: no 'static', no repeated 'Controller::'
{
cout << "Hey\n";
}
// ...
}
// ...
(For the record, what you current
Controller::AlbumOps SayHey();
// ^
// space
does is locally declare a function named SayHey taking no parameter and returning a Controller::AlbumOps (search for "C++ most vexing parse").)

Related

How to get the caller's class name inside a function without passing it as a parameter?

Goal:
To get the caller's class name inside a function, without passing
the caller's information as parameter to the function.
Problem:
I have searched online for days, and I have not found a proper way to get the class name inside a function without passing the caller's information (such as class instance, class name as string, etc.) as a parameter.
Example:
// A.h
// This is Macro Function
#define Print_Data_Macro_Function()
Print_Data_Template()
template<typename T>
void Print_Data_Template()
{
// ... do some stuff
std::cout << "The class that calls Print_Data_Macro_Function() is " << **[Caller's Class Name]** << "\n";
}
// B.cpp
#include "A.h"
void B::do_something()
{
Print_Data_Macro_Function();
}
// Main.cpp
#include "B.h"
int main()
{
B b_object;
b_object.do_something();
return 0;
}
// Output I want:
The class that calls Print_Data_Macro_Function() is B
From C++20, you can use std::source_location, which gives the name of the calling function via function_name, which includes the name of the class to which the function belongs.
void Print_Data_Template(const std::source_location location =
std::source_location::current())
{
std::cout << location.function_name() << '\n';
}
which prints
void B::do_something()
for your example snippet. demo.
You could do some additional string parsing to get just the name of the class, though I think the exact format of the returned string is not specified.

C++ what's the best way to make some functions inside source file private?

// myclass.h
#pragma once
void publicFunction();
//------
// myclass.cpp
#include "myclass.h"
#include <iostream>
void privateFunction() {
std::cout << "Hello world\n";
}
void publicFunction() {
privateFunction();
}
//-------
// main.cpp
#include "myclass.h"
#include <iostream>
void privateFunction() {
std::cout << "Hello main\n";
}
int main()
{
privateFunction();
}
The above program will fail to compile (privateFunction(void) already defined in myclass.obj). One way to solve this problem is by defining a namespace inside the source file:
#include "myclass.h"
#include <iostream>
namespace MyClass
{
void privateFunction();
// add a bunch other private functions here
}
void MyClass::privateFunction() {
std::cout << "Hello world\n";
}
//---
using namespace MyClass;
void publicFunction() {
privateFunction();
}
Is this the correct way to solve this problem? I feel like this might cause some problems later, but I don't know what is the correct way.
If you declare a function in a header file, it's not that private to begin with. If privateFunction is supposed to be an implementation detail, consider declaring it only in the translation unit. To this end, you have two common options.
Use an anonymous namespace in the implementation file.
namespace {
void privateFunction() {
std::cout << "Hello world\n";
}
}
This way, you can call privateFunction() from publicFunction, still guarding any usage of privateFunction from outside of the compilation unit.
Make the function static within the translation unit.
static void privateFunction() {
std::cout << "Hello world\n";
}
which has the same effect as 1.
Choosing among 1. and 2. is mostly a matter of taste. If you like to order function definitions such that called functions appear below the calling ones, go with 2., as 1. enforces function definitions at the point of their declarations.
Note that a drawback of such isolation is a reduced ability to write specific unit tests for the helper functions, as you cannot link against those from "outside".
Solution 1:
Declare the function static.
static void privateFunction() { ... }
Solution 2:
Declare the function inside an unnamed namespace.
namespace {
void privateFunction() { ... }
}
In both cases the function gets internal linkage, meaning it's visible only within the translation unit.
Another way is using class and inside the class you can use "private" and "public" to separate your functions and variables.

A class member function calling a class friend function (all same class) Possible?

I have a pretty basic class with member functions and private data, but I want the print function not to be a part of the class member functions. I remove it from the class and declare it as a friend and it works when called directly from main.cpp, but when a class member function calls it internally it is not declared. I know being a friend gives it access to data, but how do I make it available to the member functions? Is it possible?
//HEADER FILE
#include<iostream>
using namespace std;
static const int ArrSize=3;
class TicTacToe
{
//friends
friend void printBoard(char [][ArrSize]);
//member functions
public:
void makeboard();
void isValidMove();
void isWinner();
void getMove();
//data members
private:
int pRow, pCol, player;
bool validMove, winner;
char TTTarray[ArrSize][ArrSize];
};
void TicTacToe::getMove()
{
// some internal code for determining if proper input
// calls printBoard() to show what move was made.
printBoard(0);
void printBoard(char TTTarray[][ArrSize])
{
int i;
for(i=0;i<3;i++)
{
cout << TTTarray[i][0] << " " << TTTarray[i][0] << " " << TTTarray[i][2] << endl;
}
}
// MAIN.CPP FILE
#include <iostream>
#include "TicTacToe.h"
using namespace std;
int main()
{
TicTacToe a;
a.makeBoard();
printBoard(0);
a.getMove();
return 0;
}
At the point where you use printBoard inside getMove, printBoard indeed hasn't been declared. You need to either move the definition of printBoard before getMove (with the definition available, it is also declared) or add at least a declaration
void printBoard(char [][ArrSize]);
outside the class (also before you use it anywhere). In addition, your code does not compile because there is at least one typo (upper case, lower case makeBoard), the definition of makeBoard is missing and the closing brace of getMove is missing. Also, maybe you want to call printBoard with TTTarray instead of 0?
PS: Please post code with proper indentation next time. It is really hard to check whether parentheses balance like this...

Function calls with class members?

Before I present the code which is found at the bottom of this post I would like to talk about the issue and the fix's that I do not desire. Okay basically I've created a GUI from scratch sort of and one requirement I wanted for this was allow components to have their own click executions so if i click a button or tab etc.. It would call Component->Execute(); Well normally you would do something like a switch statement of ids and if that components ID equaled n number then it would perform this action. Well that seemed kinda dumb to me and I thought there has to be a better way. I eventually tried to incorporate a feature in JAVA where you would do like Component.AddActionListener(new ActionListener( public void execute(ActionEvent ae) { })); or something like that and I thought that this feature has to be possible in C++. I eventually came across storing void functions into a variable in which could be executed at any time and modified at any time. However I hadn't noticed an issue and that was this only worked with static functions. So below you'll see my problem. I've patched the problem by using a pointer to SomeClass however this would mean having an individual function call for every class type is there no way to store a function callback to a non-static class member without doing the below strategy? and instead doing a strategy like the commented out code?
//Main.cpp
#include <iostream> //system requires this.
#include "SomeClass.h"
void DoSomething1(void)
{
std::cout << "We Called Static DoSomething1\n";
}
void DoSomething2(void)
{
std::cout << "We Called Static DoSomething2\n";
}
int main()
{
void (*function_call2)(SomeClass*);
void (*function_call)() = DoSomething1; //This works No Problems!
function_call(); //Will Call the DoSomething1(void);
function_call = DoSomething2; //This works No Problems!
function_call(); //Will Call the DoSomething2(void);
SomeClass *some = new SomeClass(); //Create a SomeClass pointer;
function_call = SomeClass::DoSomething3; //Static SomeClass::DoSomething3();
function_call(); //Will Call the SomeClass::DoSomething3(void);
//function_call = some->DoSomething4; //Non-Static SomeClass::DoSomething4 gives an error.
//function_call(); //Not used because of error above.
function_call2 = SomeClass::DoSomething5; //Store the SomeClass::DoSomething(SomeClass* some);
function_call2(some); //Call out SomeClass::DoSomething5 which calls on SomeClass::DoSomething4's non static member.
system("pause");
return 0;
}
//SomeClass.hpp
#pragma once
#include <iostream>
class SomeClass
{
public:
SomeClass();
~SomeClass();
public:
static void DoSomething3(void);
void DoSomething4(void);
static void DoSomething5(SomeClass* some);
};
//SomeClass.cpp
#include "SomeClass.h"
SomeClass::SomeClass(void)
{
}
SomeClass::~SomeClass(void)
{
}
void SomeClass::DoSomething3(void)
{
std::cout << "We Called Static DoSomething3\n";
}
void SomeClass::DoSomething4(void)
{
std::cout << "We Called Non-Static DoSomething4\n";
}
void SomeClass::DoSomething5(SomeClass *some)
{
some->DoSomething4();
}
Secondary Fix for what I'll do not an exact answer I wanted but it meets my needs for now along with allowing additional features which would have become overly complicate had this not existed.
//Component.hpp
#pragma once
#include <iostream>
#include <windows.h>
#include <d3dx9.h>
#include <d3d9.h>
#include "Constants.hpp"
#include "ScreenState.hpp"
#include "ComponentType.hpp"
using namespace std;
class Component
{
static void EMPTY(void) { }
static void EMPTY(int i) { }
public:
Component(void)
{
callback = EMPTY;
callback2 = EMPTY;
callback_id = -1;
}
Component* SetFunction(void (*callback)())
{
this->callback = callback;
return this;
}
Component* SetFunction(void (*callback2)(int), int id)
{
this->callback_id = id;
this->callback2 = callback2;
return this;
}
void execute(void)
{
callback();
callback2(callback_id);
}
}
The syntax for pointers-to-member-functions is as follows:
struct Foo
{
void bar(int, int);
void zip(int, int);
};
Foo x;
void (Foo::*p)(int, int) = &Foo::bar; // pointer
(x.*p)(1, 2); // invocation
p = &Foo::zip;
(x.*p)(3, 4); // invocation
Mind the additional parentheses in the function invocation, which is needed to get the correct operator precedence. The member-dereference operator is .* (and there's also ->* from an instance pointer).

How do I call a function in a different namespace?

I have a function called testin namespace buzz.
From this test function i am calling another function called dummy which is inside namespace example.
I get the following error:
Dummy is not a member of example.
Can you please tell me how to communicate between 2 different namespaces?
Thanks
Following code works with gcc (as expected). Your problem must be with something that is not in the question.
#include <iostream>
namespace example
{
void dummy() { std::cout << "Dummy\n"; }
}
namespace buzz
{
void test() { example::dummy(); }
}
int main()
{
buzz::test();
}
If the namespace is not nested, you should start navigating from the root one, i.e.:
Instead of:
example::dummy
Write:
::example::dummy
You need to provide code for this query. Otherwise just from your question, I guess you are making spelling error:
namespace example {
void dummy() {}
}
namespace buzz {
void test () { example::Dummy(); } // capital 'D' instead of 'd' for dummy
}
Naturally, Dummy is not a member of example. :))