Hello,

Please help me in my query below:

Code snippet 1:

Employee *e1 = new Employee(this);
e1->setX();
e1->setY();

Code snippet 2:

Employee e1 = new Employee();
e1->setX(this);
e1->setY(this);

"this" can be anything. Example, this code is present in a method of another class say Organization. so, "this" is an object of type organization.

Question:
1. Which one is a better approach?
2. Is this a an example of strong / weak coupling. Which one is a tight coupling and which one is the loose coupling?

Recommended Answers

All 2 Replies

Please don't use "this" as an example to mean "anything at all". "this" is a C++ keyword with a specific meaning.

Employee e1 = new Employee(); // will not work

new returns a pointer. You cannot assign a pointer to a non-pointer variable.

You could do this:

Employee e1;
         e1.setX(someValue);
         e1.setY(someValue);

with some kind of overloaded setX and setY function.

These two code snippets do different things, and call different functions. The first one you posted could be said to be better in that it will actually compile, but your first one uses a different constructor to the second one. They're two completely different pieces of code that do different things.

2. Is this a an example of strong / weak coupling. Which one is a tight coupling and which one is the loose coupling?

I'd say it's an example of a lack of understanding of constructors and pointers, and two completely different pieces of code that do different things.

I intended to use "this" as the keyword and not anything generic. And I have used it in the correct context.

My apologies for:

Employee e1 = new Employee(); // will not work

corrected code below:

Employee *e1 = new Employee();
e1->setX(this);
e1->setY(this);

In first case, "this" pointer indicates object of class Organization. It is passed to Employee at the time of object construction.
You can say, Employee has a pointer to Organization class as its member. Example:

class Organization
{
	public:
	void someMethod()
	{
		Employee *e1 = new Employee(this);
		e1->setX();
		e1->setY();
	}
}

In second case, it is passed to two methods of Employee class instead of passing it to constructor.

class Organization
{
	public:
	void someMethod()
	{
		Employee *e1 = new Employee();
		e1->setX(this);
		e1->setY(this);
	}
}

As far as I can logically conclude, case 1 is an example of tight coupling and the second one of loose coupling.
Generally its advisable to have the design loosely coupled, however in the cases above, I think Case1 is a better
approach because binding with "this" happens at single place, and ensures that both methods of Employee class operate
on the same "this" object.

I need inputs from the experts here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.