Access variable from another class (in C++) - c++

This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}

Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}

In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.

It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.

Related

Classes: Instantiating Object Confusion

Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}

C++ header issue involving functions and scope

My problem is in the following C++ code. On the line with the 'cout' I get the error:
"'number' was not declared in this scope".
.h
using namespace std;
class a{
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
int main(){
cout << "Your number is: " << number() << endl;
return 0;
}
number(){
int x = 1;
return x;
}
Note: I'm aware this isn't the cleanest code. I just wanted to get the function working and refresh my memory on how to use headers.
For minimal fix, three basic changes are necessary.
Proper implementation of the number() method
int a::number() {
int x = 1;
return x;
}
Proper invocation of the number() method
a aObject;
cout << "Your number is: " << aObject.number() << endl;
There are many other enhancements possible though.
Addition, as pointed out by #CPlusPlus, usable scope of number() method, for example declaring it public
class a{
public:
int number();
};
Try this in your cpp file
using namespace std;
#include <iostream>
#include "header.h"
void a::number()
{
int x = 1;
return x;
}
int main()
{
cout << "Your number is: " << a().number() << endl;
return 0;
}
As for your header file replace class with a struct. The reason you are getting this error is because the compiler cant find the variable number. It is actually a method of a class.The reason you are replacing the class with a struct is because by default everything in a struct is public. So your header file called header.h should look like this
using namespace std;
struct a
{
int number();
};
There are three issues with your code.
The definition of the function number().
As you declared, it is a member function of the class "a". In your .cpp, the class name should be used as a prefix to the function. I mean,
a::number(){
int x = 1;
return x;
}
As the function is a member of the class "a", there are only two ways of accessing it,
If the function is a static function in the class, you can access it with :: operator. Like a::number().
If the function is not a static function, that is true in your case, you should instantiate the object out of the class "a" and they use "." operator with the reference. I mean,
a obj;
obj.number().
Your function number() is declared in private scope. You may recall that by default the scope is a class is private unless you specify public or protected. So the private function number() cannot be used outside the declared class unless there is a friend to it.
Below the code that I fixed,
.h
using namespace std;
class a{
public:
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
a::number(){
int x = 1;
return x;
}
int main(){
a obj;
cout << "Your number is: " << obj.number() << endl;
return 0;
}

C++ Error: Was not declared in the scope

Hey guys I'm working on a project and I was doing pretty well until I hit this wall..
I am getting two errors:
error: 'binarySearch' was not declared in this scope
error: 'addInOrder' was not declared in this scope
Here are my files, I've tried quite a few things with no avail. Help would be much appreciated.
histogram.cpp
#include "histogram.h"
#include "countedLocs.h"
//#include "vectorUtils.h"
#include <string>
#include <vector>
using namespace std;
void histogram (istream& input, ostream& output)
{
// Step 1 - set up the data
vector<CountedLocations> countedLocs;
// Step 2 - read and count the requested locators
string logEntry;
getline (input, logEntry);
while (input)
{
string request = extractTheRequest(logEntry);
if (isAGet(request))
{
string locator = extractLocator(request);
int position = binarySearch (countedLocs,
CountedLocations(locator, 0));
/** Hint - when looking CountedLocations up in any kind
of container, we really don't care if the counts match up
or not, just so long as the URLs are the same. ***/
if (position >= 0)
{
// We found this locator already in the array.
// Increment its count
++countedLocs[position].count;
}
else
{
// This is a new locator. Add it.
CountedLocations newLocation (locator, 1);
addInOrder (countedLocs, newLocation);
}
}
getline (input, logEntry);
}
// Step 3 - write the output report
for (int i = 0; i < countedLocs.size(); ++i)
output << countedLocs[i] << endl;
}
countedLocs.cpp
#include "countedLocs.h"
#include <iostream>
#include <vector>
using namespace std;
int CountedLocations::binarySearch(const vector<CountedLocations> list, CountedLocations searchItem)
{
//Code was here
}
int CountedLocations::addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value)
{
//Code was here
}
countedLocs.h
#ifndef COUNTEDLOCATIONS
#define COUNTEDLOCATIONS
#include <iostream>
#include <string>
#include <vector>
struct CountedLocations
{
std::string url;
int count;
CountedLocations (){
url = "";
count = 0;
}
CountedLocations(std::string a, int b){
url = a;
count = b;
}
int addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value);
int binarySearch (const std::vector<CountedLocations> list, CountedLocations searchItem);
};
inline
std::ostream& operator<< (std::ostream &out, CountedLocations& cL)
{
//out << "URL: " << cL.url << " count: " << cL.count << std::endl;
out << "\"" << cL.url << "\"," << cL.count;
return out;
}
#endif
The methods are member methods of CountedLocations... use something.extractLocator and something.binarySearch or make the histogram() to be also a member method of CountedLocations... (something is of type CountedLocations highly possibly will be countedLocs[position])
You have a free function histogram in which you are trying to use two member functions, addInOrder and binarySearch. In order to use them, you need to have an instance of CountedLocations.
If these are some kind of helper functions, which do not depend on the actual CountedLocations instance, I would turn them into static functions like this (you only need to change the header):
static int addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value);
And then you can call this function by specifying the type of your class:
CountedLocations::addInOrder(...);
You are trying to call member methods of a struct without an object of that type. Strange.
You need to look at what a namespace is.
You declare a class CountedLocations, so far so good. But then you try to use the member functions outside the CountedLocations namespace which will obviously never work.
int position = binarySearch (countedLocs,
CountedLocations(locator, 0));
binarySearch is a member function of the CountedLocations namespace. If you want to call that function you have to create an object that contains a reference to that member function.
CountedLocation myObject;
int position = myObject.binarySearch (countedLocs, CountedLocations(locator, 0));
I dont know if that solves your problem, but you should know this before you even attempt to solve a problem.

A pointer to a bound function may only be used to call the function

I'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.

"Warning: Can't find linker symbol for virtual table for value XXX value" using GCC and GDB (CodeBlocks)

I'm getting a runtime error ("memory can't be written") that, after inspection through the debugger, leads to the warning in the tittle.
The headers are the following:
componente.h:
#ifndef COMPONENTE_H
#define COMPONENTE_H
using namespace std;
class componente
{
int num_piezas;
int codigo;
char* proovedor;
public:
componente();
componente(int a, int b, const char* c);
virtual ~componente();
virtual void print();
};
#endif // COMPONENTE_H
complement.h implementation
#include "Componente.h"
#include <string.h>
#include <iostream>
componente::componente()
{
num_piezas = 0;
codigo = 0;
strcpy(proovedor, "");
//ctor
}
componente::componente(int a = 0, int b = 0, const char* c = "")
{
num_piezas = a;
codigo = b;
strcpy(proovedor, "");
}
componente::~componente()
{
delete proovedor;//dtor
}
void componente::print()
{
cout << "Proovedor: " << proovedor << endl;
cout << "Piezas: " << num_piezas << endl;
cout << "Codigo: " << codigo << endl;
}
teclado.h
#ifndef TECLADO_H
#define TECLADO_H
#include "Componente.h"
class teclado : public componente
{
int teclas;
public:
teclado();
teclado(int a, int b, int c, char* d);
virtual ~teclado();
void print();
};
#endif // TECLADO_H
teclado.h implementation
#include "teclado.h"
#include <iostream>
teclado::teclado() : componente()
{
teclas = 0;//ctor
}
teclado::~teclado()
{
teclas = 0;//dtor
}
teclado::teclado(int a = 0, int b = 0, int c = 0, char* d = "") : componente(a,b,d)
{
teclas = c;
}
void teclado::print()
{
cout << "Teclas: " << teclas << endl;
}
The main method where I get the runtime error is the following:
#include <iostream>
#include "teclado.h"
using namespace std;
int main()
{
componente a; // here I have the breakpoint where I check this warning
a.print();
return 0;
}
BUT, if instead of creating an "componente" object, I create a "teclado" object, I don't get the runtime error. I STILL get the warning during debugging, but the program behaves as expected:
#include <iostream>
#include "teclado.h"
using namespace std;
int main()
{
teclado a;
a.print();
return 0;
}
This returns "Teclas = 0" plus the "Press any key..." thing.
Do you have any idea why the linker is having troube with this? It doesn't show up when I invoke the virtual function, but before, during construction.
Two errors that I can see:
strcpy(proovedor, ""); // No memory has been allocated to `proovedor` and
// it is uninitialised.
As it is uninitialised this could be overwriting anywhere in the process memory, so could be corrupting the virtual table.
You could change this to (in both constructors):
proovedor = strdup("");
Destructor uses incorrect delete on proovedor:
delete proovedor; // should be delete[] proovedor
As this is C++ you should considering using std::string instead of char*.
If you do not change to std::string then you need to either:
Implement a copy constructor and assignment operator as the default versions are incorrect if you have a member variable that is dynamically allocated, or
Make the copy constructor and assignment operator private to make it impossible for them to be used.
Another source of this same message is that gdb can get confused by not-yet-initialized variables. (This answers the question title, but not the OP's question, since a web search led me here looking for an answer.)
Naturally, you shouldn't have uninitialized variables, but in my case gdb attempts to show function local variables even before they are declared/initialized.
Today I'm stepping through another developer's gtest case and this message was getting dumped to output every time the debugger stopped. In this case, the variable in question was declared on ~line 245, but the function started on ~line 202. Every time I stopped the debugger between these lines, I received the message.
I worked around the issue by moving the variable declaration to the top of the function.
For reference, I am testing with gdb version 7.11.1 in QtCreator 4.1.0 and I compiled with g++ version 5.4.1