Solved

C++ Object Instantiation

Posted on 2008-06-24
6
1,144 Views
Last Modified: 2013-11-12
What's the difference between the following statements in C++ and the proper situations in which one would be used over the others?

Base *obj = new Derived();
Derived *obj = new Base();
Derived *obj = new Derived();

Does it affect the way you would call a method? (i.e. obj->someMethod() )?  Let's say the method only existed in the derived class.  How does that change things?

Note:  I will be away from a computer for a while so I won't be able to respond to posts until tomorrow :-)
0
Comment
Question by:cuziyq
6 Comments
 
LVL 10

Expert Comment

by:margajet24
ID: 21856456
if your are using the "Base" as the data type and you want to call a "SubClass" function, you need to type cast it to the "SubClass" to be able to have the access right to the function.

you use the Base Class if you are not yet sure which subclass to type cast to.. since Subclass inherits from the Base Class, casting from BaseClass to SubClass is possible..

one example maybe for this is when you use a Factory Design Pattern
0
 
LVL 1

Accepted Solution

by:
Andrew_Lvov earned 65 total points
ID: 21857276
a) You won't be able to execute Derived *obj = new Base(), because object of Class base is not  Derived, vice versa is true.
b) The difference between 1. and 3. is in non-virtual functions call. Let's say void f() is non-virtual function defined in both Base and Derived classes. Then the next calls will execute f() from Base and from Derived respectively:

Base* b = new Derived();

Derived* d = new Derived();

b->f();     // would call Base::f()

d->f();     // would call Derived::f()

Open in new window

0
 
LVL 1

Expert Comment

by:Andrew_Lvov
ID: 21857314
Oh, and of course if der() is not defined in Base, you'll have a compilation error trying to call:
class Base

{

  void f();

};
 

class Derived : public Base

{

  void f();  // override, but non-virtual

  void der();

};
 

main()

{

  Base* b = new Derived();

  b -> der();     // would lead to compilation error
 

  return 0;

}

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 17

Assisted Solution

by:rstaveley
rstaveley earned 60 total points
ID: 21857854
Best to experiment. The following shows you some static invocation too...
#include <iostream>

#include <string>

using std::string;

using std::cout;
 

class base;

std::ostream& operator<<(std::ostream& os,const base& b);

class base {

	string name;

	friend std::ostream& operator<<(std::ostream& os,const base& b);

public:

	void f() {

		cout << *this << ".base::f()\n";

	}

	virtual void v() {

		cout << *this << ".base::v()\n";

	}

	base(const string& name) : name(name) {}

	virtual ~base() {}

};
 

std::ostream& operator<<(std::ostream& os,const base& b)

{

	return os << b.name;

}
 

class derived : public base {

	string name;

	friend std::ostream& operator<<(std::ostream& os,const base& b);

public:

	void f() {

		cout << *this << ".derived::f()\n";

	}

	virtual void v() {

		cout << *this << ".derived::v()\n";

	}

	derived(const string& name) : base(name) {}

};
 

int main()

{

	{

		base *obj = new base("alpha-base");

		obj->f();

		obj->v();

		obj->base::f();

		obj->base::v();

		delete obj;

	}

	{

		derived *obj = new derived("beta-derived");

		obj->f();

		obj->v();

		obj->base::f();

		obj->base::v();

		obj->derived::f();

		obj->derived::v();

		delete obj;

	}

	{

		base *obj = new derived("gamma-derived");

		obj->f();

		obj->v();

		obj->base::f();

		obj->base::v();

		//obj->derived::f();	// Compiler error

		//obj->derived::v();	// Compiler error

		delete obj;

	}

	

}

Open in new window

0
 
LVL 17

Expert Comment

by:rstaveley
ID: 21857925
Seriously though my point is  that you'll understand and learn this stuff best by experimentation. See what happens when you invoke virtual and non-virtual functions in a polymorphic object. See what happens when the static type is base and when the static type is derived. It is much better learning that way than hearing about it from know-it-alls like me.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 21857975
The behavior you see when calling a method on a base class will depend on whether that method is virtual or not. If it is you'll get polymorphic behavior.
http://www.cplusplus.com/doc/tutorial/polymorphism.html
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
System Development Similar to ERP 9 54
MFC Dialog 9 48
Embarcadero C++ Builder XE2 TDateTime 8 61
Compile GLUT with Visual Studio 2015 1 108
Software development teams often use in-memory caches to improve performance. They want to speed up access to, or reduce load on, a backing store (database, file system, etc.) by keeping some or all of the data in memory.   You should implement a …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now