-
improve this cpp code?
I need to improve this code.
any suggestions?
Code:
class Foo
{
public:
virtual void func() const = 0;
};
class Bar: public Foo
{
public:
Bar(): data (new int[10]) ()
~Bar() {}
void func() const{
data++;
}
int get()
{
return data;
}
private:
int *data;
};
Foo *foo = makeBar();
foo->func():
return 0;
}
-
Indentation is a good start
-
Can someone help me as I am new to C++ and still learning it. I see the below compile errors. how to fix it? any suggestions please.
main.cpp: In member function virtual void Bar::func() const:
main.cpp:23:5: error: increment of member Bar::data in read-only object
data++;
^~
main.cpp: In member function int Bar::get():
main.cpp:27:8: error: invalid conversion from int* to int [-fpermissive]
return data;
^~~~
main.cpp: At global scope:
main.cpp:32:20: error: makeBar was not declared in this scope
Foo *foo = makeBar();
^
main.cpp:33:1: error: foo does not name a type
foo->func():
-
this is full code...
Code:
#include <iostream>
using namespace std;
class Foo
{
public:
virtual void func() const = 0;
};
class Bar: public Foo
{
public:
Bar(): data (new int[10]) ()
~Bar() {}
void func() const{
data++;
}
int get()
{
return data;
}
private:
int *data;
};
Foo *foo = makeBar();
foo->func():
return 0;
}
int main()
{
cout<<"Hello World";
return 0;
}
-
The code doesn't really make sense.
What do you want it to do?
-
I need to improve the code as it gives some compile errors...Need to fix them.
-
Need to improve the below code.
Code:
class Foo
{
public:
virtual void func() const = 0;
};
class Bar: public Foo
{
public:
Bar(): data (new int[10]) ()
~Bar() {}
void func() const{
data++;
}
int get()
{
return data;
}
private:
int *data;
};
Foo *foo = makeBar();
foo->func():
return 0;
}
-
-
Quote:
Originally Posted by
leo2008
Any suggestions here?
Write code that makes sense.
-
If you have an abstract function in the base class you need a virtual constructor.
c++ - When to use virtual destructors? - Stack Overflow
I also would replace the dynamic array with a std::vector.
std::array - Dynamic Memory, no Thanks - ModernesCpp.com
-
> Can someone help me as I am new to C++ and still learning it.
Yeah, since 2008 apparently - when you first joined.