0

I have wondered that both c++ and java using oops concepts but the syntaxes are quite different.

I found that java uses new ClassName() to get a reference to the heap but getting the same reference to the heap why the c++ uses new ClassName.

 #include<iostream>
 using namespace std;

class Bike
{
public:
    virtual  void run()
    {
        cout << "running";
    }
};

class Splender :public Bike
{
public:
    void run()
    {
        cout << "running safely with 60km";
    }
};

int main()
{
    Bike &obj = new Splender();//error but reason?
    obj.run();
}

ERROR: invalid initialization of non-const reference of type 'Bike&' from an rvalue of type 'Splender*'

3 Answers3

1

Two things. One: Operator new returns a pointer, not a reference, to an object instance. So use Bike* obj = new Splender();

Two: Do not get cute and try Bike& obj = *new Splender(); because new can return nullptr in a low memory situation and if you dereference it, your program will crash at that point. (And you are forced to use the ugly delete *obj; to clean up this object as user4581301 points out in the comments.)

Oh, and using namespace std is a bad practice. It won't kill you to add std:: in the places you use the standard library.

jmucchiello
  • 18,754
  • 7
  • 41
  • 61
  • "your program will crash at that point." Not necessarily. This be Undefined Behaviour. It could look like it worked or rain unicorns. – user4581301 Mar 20 '18 at 17:25
  • Dereferencing null in every C++ implementation I've ever used (including one running on MVS on an IBM Mainframe) causes a crash (or ABEND on MVS). There are times when the strict definition of Undefined Behavior can step aside for practice real-world experience. – jmucchiello Mar 20 '18 at 17:28
  • Gotta give you that. Can't remember the last time I didn't crash over a null. Worth noting that it's more likely `new` will `throw` or die trying to `throw` than return a `nullptr`. – user4581301 Mar 20 '18 at 17:32
  • Well, in a modern compiler, throwing is more likely. But in extreme low memory situations, you can still get null. Also, there are switches on most compilers to disable exceptions (both globally and specifically inside `new`.) – jmucchiello Mar 20 '18 at 18:39
0
#include <iostream>

class Bike {
public:
    virtual void run() {
        std::cout << "running";
    }
    virtual ~Bike() {}
};

class Splender: public Bike {
public:
    void run() override {
        std::cout << "running safely with 60km";
    }
};

int main() {
    Bike *obj = new Splender(); // new returns a pointer to a dynamically allocated object
    obj->run();
    delete obj;
}

which displays:

running safely with 60km

Ron
  • 14,674
  • 4
  • 34
  • 47
Benjamin Barrois
  • 2,566
  • 13
  • 30
0

Sometimes we think doing the right thing. You make a bit confusion. Try:

Bike *obj=new Splender();
Ratah
  • 299
  • 3
  • 11