This is my code. I created base class and in constructor set x=0. Next I used virtual set_x() = 0. And I created set_x() in new class. Output:
set x
100
DONE. Let's check. 0500
Why I got 0500 not 100500?
#include "mainwindow.h"
#include <QApplication>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
struct invalid_file_handler : std::runtime_error{
using runtime_error::runtime_error;
};
class base_class{
private:
int x;
int y;
public:
virtual void set_x()=0;
void set_y(){
this->y=500;
}
int get_x(){
return (this->x);
}
int get_y(){
return (this->y);
}
base_class(){
this->x=0;
this->y=0;
}
};
class new_class :public base_class{
public:
void set_x();
private:
int z;
int x;
int y;
};
void new_class::set_x(){
cout << "set x " << endl;
this->x=100;
cout << this->x << endl << "DONE. Let's check. ";
}
int main()
{
ifstream my_open_file;
string file_path = "/home/wojtek/Pulpit/elo.odt";
try{
my_open_file.open("/home/wojtek/Pulpit/elo.odt");
my_open_file.close();
}catch (std::runtime_error &e){
cerr << "Hello Xd XD chua" << endl;
cerr << e.what();
}
ofstream myfile;
try{
myfile.open ("/home/wojtek/Pulpit/example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
}
catch(invalid_file_handler &e){
cerr << "Hello!" << endl;
}
new_class *object = new new_class();
object->set_x();
cout << object->get_x();
object->set_y();
cout << object->get_y();
//base_class object;
//cout << object.get_y();
return 0;
}
The variables x and y declared in new_class are shadowing the variables with the same names declared in base_class. This means that in any member method of new_class, the name x refers to new_class::x and not base_class::x.
Simply remove these lines from the new_class definition:
int x;
int y;
And make the same members in the base_class protected instead of private so that the new_class also has access:
class base_class{
protected:
int x;
int y;
Note: your code has a memory leak, since you never delete object after allocating it. Always delete what you new, and don't use new unless you really need to.
Related
I am working on a class assignment to create three classes nested inside each other. I need to make constructors and deconstructors for each that have a message that goes along with them. Finally, I need to create an instance of each class using new and call the display() function to show their message, followed by delete.
I have completed the assignment but in the wrong way, and I am confused about how I can properly put the code into the heap instead of the stack (as I was advised by my course tutor).
This is what I started with: (this code seems to work well, but does not fulfill the assigned project)
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Hen {
public:
Hen();
~Hen();
string display(void) {
return ("Im a Hen");
}
class Nest;
friend Nest;
class Nest {
public:
Nest();
~Nest();
string display(void) {
return ("Im a Nest");
}
class Egg;
friend Egg;
class Egg {
public:
Egg();
~Egg();
string display(void) {
return ("Im an egg");
}
};
};
};
Hen::Hen() {
cout << "I construct Hens" << endl;
}
Hen::~Hen() {
cout << "I deconstruct Hens" << endl;
}
Hen::Nest::Nest() {
cout << "I construct Nests" << endl;
}
Hen::Nest::~Nest() {
cout << "I deconstruct Nests" << endl;
}
Hen::Nest::Egg::Egg() {
cout << "I construct Eggs" << endl;
}
Hen::Nest::Egg::~Egg() {
cout << "I deconstruct Eggs" << endl;
}
int main() {
Hen hone;
Hen::Nest none;
Hen::Nest::Egg eone;
string h, n, e;
h = hone.display();
n = none.display();
e = eone.display();
cout << h << "\n" << n << "\n" << e << endl;
}
Where I am stuck is when I try to implement my code inside the heap, it seems to break by the second class:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Hen {
public:
void display() {
cout << "Im a Hen" << endl;
}
class Nest;
friend Nest;
class Nest {
public:
void display() {
cout << "Im a Nest" << endl;
}
class Egg;
friend Egg;
class Egg {
public:
void display() {
cout << "Im an egg" << endl;
}
};
};
};
int main() {
Hen *hone = new Hen();
Hen::Nest *none = new Nest();
hone -> display();
none -> display();
}
Question 1:
If I remove all the information related to nest, the program runs Hen just fine and returns the "I'm a hen" statement. But, when I add in nest, the warning I recieve is
"error: expeected type-specifier before 'Nest'
Hen::Nest *none = new Nest();"
I do not understand what I am doing wrong as I did the exact same process for Hen and it worked. I do know that the error must be in the way Nest gets called through hen?
I apologize if this question is obvious, but I am just starting c++ and do not understand why I am getting these messages...
Thanks for your help!
i'm new to this site, after doing some research I could not find a problem similar to mine(some questions looked like mine but their code was different)
So basically what i'm trying to do is to representing the framebuffer matrix with all different colors values. I'm coding a class named "Point", and I have one constructor, using default arguments, here it is :
Point.h
#ifndef POINT_H
#define POINT_H
#include <iostream>
class Point
{
protected:
int x;
int y;
public:
Point(int=0,int=0);
Point(const &Point);
void showC() const;
static void showC(Point);
virtual ~Point();
};
#endif // POINT_H
Point.cpp
#include "Point.h"
using namespace std;
Point::Point(int a,int b)
{
x=a;
y=b;
}
Point::~Point()
{}
void Point::showC() const
{ cout << x << " " << y << endl; }
void Point::showC(Point P)
{ cout << P.x << " " << P.y << endl; }
But the problem is when I try to compile the program
main.cpp
#include <iostream>
#include "Point.h"
using namespace std;
int main()
{
Point P1;
Point P2(2);
Point P3(4,-7);
cout << "Call of function member showC\n";
P1.showC();
P2.showC();
P3.showC();
cout << "Call of static function showC\n";
Point::showC(P1);
Point::showC(P2);
Point::showC(P3);
return 0;
}
There is an error when I create Point P2 :
"Call of overloaded 'Point(int)' is ambigous"
On all the others question i read, either it was not the same problem or they had a default constructor in addition to a constructor with default argument which cause ambiguity of which constructor to use if you create an object without argument.
On a book i'm reading to improve skills on c++, there is this sample that is working somehow, and that's why I don't really understand
Here is the sample :
main.cpp
class point
{
private :
int x;
int y;
Point (int abs=0, int ord=0) //inline constructor
{x=abs; y=ord;}
bool coincide(point);
};
bool point::coincide(point pt)
{ return ( (pt.x==x) && (pt.y==y) );
}
int main()
{
point a, b(1), c(1,0);
cout << "a and b : " << a.coincide(b) << " ou " b.coincide(a) << "\n"
cout << "b et c : " << b.coincide(c) << " ou " << c.coincide(b) << "\n"
}
However he grouped everything in the main.cpp files, and his constructor is inline.
Can anyone explain to me why is the sample working, and why my program is not ? I guess there is a mechanism that i don't understand...
Thanks in advance
RE-EDIT : I copied all the code
I think you are mixing both python and c++ way of creating class
python do use : class Point:
for declaring in class , c++ uses {} like class Point {};
Below works by changing the class declaration.
Just added a cout in your constructor
#include <iostream>
#include <vector>
using namespace std;
class Point
{
private:
int x;
int y;
public:
Point(int=0,int=0);
};
Point::Point(int a, int b)
{
x = a;
y = b;
cout<<x<<y<<endl;
}
int main()
{
Point P1;
Point P2(2);
Point P3(4,-7);
return 0;
}
Output
00
20
4-7
Program ended with exit code: 0
After question edit
Removed your buggy line and it works perfectly
Point(const &Point);
#include <iostream>
#include <vector>
using namespace std;
class Point
{
protected:
int x;
int y;
public:
Point(int=0,int=0);
//Point(const &Point);
void showC() const;
static void showC(Point);
virtual ~Point();
};
Point::Point(int a,int b)
{
x=a;
y=b;
}
Point::~Point()
{}
void Point::showC() const
{ cout << x << " " << y << endl; }
void Point::showC(Point P)
{ cout << P.x << " " << P.y << endl; }
int main()
{
Point P1;
Point P2(2);
Point P3(4,-7);
cout << "Call of function member showC\n";
P1.showC();
P2.showC();
P3.showC();
cout << "Call of static function showC\n";
Point::showC(P1);
Point::showC(P2);
Point::showC(P3);
return 0;
}
Output
Call of function member showC
0 0
2 0
4 -7
Call of static function showC
0 0
2 0
4 -7
Program ended with exit code: 0
After edit I guess you want to use copy constructor just change it to
Point(const Point &p2) {x = p2.x; y = p2.y; }
When i use this code bellow: exception error is not print out screen when I using g++ in Ubuntu but when i change to Dev C in C++.
#include <iostream>
#include <exception>
#include <stdexcept>
#include <string.h>
#include <sstream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Define Class for exception error
class NoBinaryNumber: public logic_error{
private:
string s;
int x;
public:
NoBinaryNumber(string msg,int x) : logic_error(msg){
s = msg; this->x=x;
}
const char* what() const throw(){
ostringstream a;
a.str("");
a << s << " is wrong at position "<< x;
if(a)
return a.str().c_str();
else
return "";
}
~NoBinaryNumber() throw(){};
};
class BinaryStringToNumber{
public:
int number;
BinaryStringToNumber(string s){
number=0;
for (int i=s.length()-1;i>=0;i--){
if ((s[i]=='1')||(s[i]=='0')){
number=number+(s[i]-'0')*pow(2,i);
}
else{
throw NoBinaryNumber(s,s.length()-i);
cout << "alala" ;
}
}
}
};
int main(){
//Using customer exception error
try{
BinaryStringToNumber a("2");
cout << a.number << endl;
}
catch (NoBinaryNumber& e){
cout << e.what() << endl;
}
return 0;
}
The result shoud be: "2 is wrong at position 1"
In your what() function, you are creating an object (ostringstream), which is destructed at the end of this function call, and trying to access its content (a.str().c_str()) outside of what() function. This is an undefined behaviour (UB) and the fact that DevC++ is showing is just because it is an UB.
To solve this, I suggest you to create your message at constructor call and use what() just to show this message. Something like this:
class NoBinaryNumber: public logic_error{
private:
string s;
int x;
public:
NoBinaryNumber(string msg,int x) : logic_error(msg){
s = msg + " is wrong at position " << std::to_string(x);
this->x=x;
}
const char* what() const throw(){
return msg.c_str();
}
};
I'm having trouble correctly setting up and accessing my member functions of a class. This node class is being used to build a Max Heap Tree. However, when the tree is being initialized, I'm getting garbage data and not what I am initializing it to.
#ifndef HEAPNODE_H_INCLUDED
#define HEAPNODE_H_INCLUDED
#include <iostream>
#include <cstdlib>
#include <array>
using namespace std;
template <class Type> class HeapNode {
private:
int key;
Type value;
public:
HeapNode(int key, Type const &value) {
this->key = key;
this->value = value;
}
// Returns the key of the node
int getKey() {
return key;
}
// Returns the value of the node
Type getValue() {
return value;
}
// Displays the node
void displayNode() {
cout << "Key: " << key << "\tValue: " << value << endl;
}
};
#endif
Here is the class that builds my Heap Tree. I've tried setting the initializations in the constructor every which way, and I'm still getting junk data. In addition, I set the constructor to take an integer, but when I'm creating a tree in my driver program, it won't let me put an argument for it which initiates an array of that size.
#ifndef MAXHEAPTREE_H_tINCLUDED
#define MAXHEAPTREE_H_INCLUDED
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "HeapNode.h"
using namespace std;
template <class Type> class MaxHeapTree {
private:
HeapNode<Type> *array;
HeapNode<Type> *root;
int elementSize;
int height;
int leafCounter;
public:
// Constructor
MaxHeapTree(int n = 10) : elementSize(0), height(0), leafCounter(0) {
this->elementSize = elementSize;
this->height = height;
this->leafCounter = leafCounter;
HeapNode<Type> *array = new HeapNode<Type>[n];
}
// Destructor
~MaxHeapTree();
void arrayDisplay() {
cout << "Original array size: " << sizeof(array)/4 << endl;
}
// Returns the number of elements in the tree
int getSize() {
return elementSize;
}
// Returns the height of the tree
int getHeight() {
return height;
}
// Returns the number of leaves in the tree
int leaves() {
return leafCounter;
}
int countLines(const string fileName) {
string line;
int lineCount = 0;
ifstream myFile (fileName.c_str());
if (myFile.is_open()) {
while (getline(myFile, line)) {
lineCount++;
}
}
else {
cout << "Error opening file" << endl;
}
myFile.close();
return lineCount;
}
// Reads structure from a text file and builds a max heap
void buildTree(const string fileName) {
string line;
string key;
string value;
int lines = countLines(fileName);
int i = 0;
cout << "Lines: " << lines << endl;
HeapNode<Type> *newArray[lines];
cout << "Size of newArray: " << sizeof(newArray)/4 << endl;
ifstream myFile (fileName.c_str());
if (myFile.is_open()) {
while (getline(myFile, line)) {
key = line.substr(0, 1);
int x = atoi(key.c_str());
value = line.substr(1);
HeapNode<Type> *hNode = new HeapNode<Type>(x, value);
newArray[i] = hNode;
cout << "newArray[" << i << "] = ";
newArray[i]->displayNode();
i++;
}
}
else {
cout << "2 - Error opening file." << endl;
}
myFile.close();
}
};
#endif
How do you initialize template class members that uses other template classes?
In the same way you initialize members of non templates that don't use other templates.
when the tree is being initialized, I'm getting garbage data and not what I am initializing it to.
I was using MaxHeap<string> *heapTree1;
Well, there's your problem. Apparently you never created an instance of MaxHeap<string>.
Why does this work:
#include "iostream"
class Something {
private:
static int s_nIDGenerator;
int m_nID;
friend int main();
public:
Something() { m_nID = s_nIDGenerator++; }
int GetID() const { return m_nID; }
};
int Something::s_nIDGenerator;
int main() {
Something::s_nIDGenerator = 1;
Something cFirst;
Something cSecond;
Something cThird;
using namespace std;
cout << cFirst.GetID() << endl;
cout << cSecond.GetID() << endl;
cout << cThird.GetID() << endl;
return 0;
}
it prints:
1
2
3
And this fail:
#include "iostream"
namespace test {
class Something {
private:
static int s_nIDGenerator;
int m_nID;
friend int main();
public:
Something() { m_nID = s_nIDGenerator++; }
int GetID() const { return m_nID; }
};
};
int test::Something::s_nIDGenerator;
int main() {
using namespace test;
Something::s_nIDGenerator = 1;
// or test::Something::s_nIDGenerator = 1; same effect if not using using.
Something cFirst;
Something cSecond;
Something cThird;
using namespace std;
cout << cFirst.GetID() << endl;
cout << cSecond.GetID() << endl;
cout << cThird.GetID() << endl;
return 0;
}
With the compiler error message of:
**** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\tuttest1.o ..\src\tuttest1.cpp
..\src\tuttest1.cpp: In function 'int main()':
..\src\tuttest1.cpp:23:5: error: 'int test::Something::s_nIDGenerator' is private
..\src\tuttest1.cpp:27:13: error: within this context
Build error occurred, build is stopped
Time consumed: 161 ms.
How do I get the 2nd example to work using the namespace test?
How/Why is the namespace declaration around the object preventing the static member form being accessible?
Per my comment to #zmo, here is what I got to work based on his clue:
(comment doesn't have the space or formatting for this, and I had to edit because I couldn't set this an answer.... (what ever it takes.)
#include "iostream"
namespace test {
class Something {
private:
static int s_nIDGenerator;
int m_nID;
friend void load(int);
public:
Something() { m_nID = s_nIDGenerator++; }
int GetID() const { return m_nID; }
};
int Something::s_nIDGenerator;
void load (int value) {
Something::s_nIDGenerator = value;
}
};
int main() {
using namespace test;
load (1);
Something cFirst;
Something cSecond;
Something cThird;
using namespace std;
cout << cFirst.GetID() << endl;
cout << cSecond.GetID() << endl;
cout << cThird.GetID() << endl;
return 0;
}
I am still a little loose as to the "what's up with static members being in a class and a namespace not working?" What's up with this? Why didn't test::Something::s_nIDGenerator work? (still a part of my original question.) So, we are half-answered, so far.
I want to know why this didn't work so I don't walk into this rake again.
Probably because your friend int main() declaration is declaring that the namespace also has a free main() function, while the real main() function is not in the namespace.
To fix it? First declare int main(); before (and outside) namespace test, then friend int ::main() to indicate it's in the global namespace.
For more details, see this question.
well, though I will never recommand you to do like you did in your question, here is how to make your code work "as is" :
#include <iostream>
int main(); // declare main beforehands so it can be seen by Something
namespace test {
class Something {
private:
static int s_nIDGenerator;
int m_nID;
friend int ::main(); // take the main from global namespace
public:
Something() { m_nID = s_nIDGenerator++; }
int GetID() const { return m_nID; }
};
};
int test::Something::s_nIDGenerator;
int main() {
using namespace test;
Something::s_nIDGenerator = 1; // tada that works
Something cFirst;
Something cSecond;
Something cThird;
using namespace std;
cout << cFirst.GetID() << endl;
cout << cSecond.GetID() << endl;
cout << cThird.GetID() << endl;
return 0;
}
but here is a wrong use case of a friend function. The solution that seemed to work for you that I suggested (use a function inside your class Something) is far better for readability and understandability.