473,791 Members | 3,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem related to overloading == operator

Hi, I have developed one class called CProductInfo providing == and !=
operator features. I have one problem.

When I use this class in my program, say

CProductInfo product = null;

and later, when i check for emptiness,

if (product==null)

it returns false as if the product instance is not empty.

I tried various ways to eliminate this run-time error, but it just does
not happen. Also I don't think there is use full tips on net for this.

Can someone help?

Thanks in advance - Rhonald

<<<< THE SOURCE CODE FOR CProductInfo IS BELOW >>>>>


using System;
using System.Data;
using System.Data.Sql Client;
using MyDataLibrary;

namespace ProductManager2 006
{
/// <summary>
/// Summary description for CProductInfo.
/// </summary>
public class CProductInfo:Co nnectionManager
{
internal long m_AutoIndex = 0;
internal string m_SerialNumber = "";
public string Title = "";
private DateTime m_DateReference = DateTime.Now;
private DateTime m_DateStart = DateTime.Now, m_DateFinish =
DateTime.Now;
public ProductType Type = ProductType.Cus tomizedProduct;
public string Version = "", Build = "", Explanation = "";
public string Notes = "", Features = "", SystemRequireme nts = "",
PreRequisites = "";
public bool Status = true;
private bool m_IsDateStartAv ailable = false, m_IsDateFinishA vailable
= false;

public CProductInfo()
{
//
// TODO: Add constructor logic here
//
}

public CProductInfo(st ring productId)
{
Open(productId) ;
}

public CProductInfo(Da taRow dr)
{
if (dr!=null)
{
m_AutoIndex = DataConverter.T oLong(dr["auto_index "].ToString());
m_SerialNumber = dr["pk_product _id"].ToString();
m_DateReference =
Convert.ToDateT ime(dr["date_reference "].ToString());
Title = dr["title"].ToString();

if (!dr.IsNull(4)) DateStart =
Convert.ToDateT ime(dr["date_start "].ToString());
if (!dr.IsNull(5)) DateFinish =
Convert.ToDateT ime(dr["date_finis h"].ToString());

Type =
DataConverter.T oBoolean(dr["product_ty pe"].ToString())?Pr oductType.Gener alizedProduct:P roductType.Cust omizedProduct;

Version = dr["version"].ToString();
Build = dr["build"].ToString();
Notes = dr["notes"].ToString();
Features = dr["features"].ToString();
SystemRequireme nts = dr["system_require ments"].ToString();
PreRequisites = dr["prerequisi tes"].ToString();
Status = DataConverter.T oBoolean(dr["status"].ToString());
}
}

private string _NewID
{
get
{
SqlCommand cmdSql = new SqlCommand("sel ect isnull(max(auto _index),
0) as counter from mstrproducts", Connection);

try
{
OpenConnection( );

SqlDataReader dr = cmdSql.ExecuteR eader();

if (dr.Read())
{
return
((DataConverter .ToInteger(dr["counter"].ToString())+1) .ToString("0000 0"));
}
}
catch(Exception ex)
{
Console.WriteLi ne(ex.ToString( ));

return null;
}
finally
{
CloseConnection ();
}

return null;
}
}

public string SerialNumber
{
get
{
return m_SerialNumber;
}
}

public DateTime DateReference
{
get
{
return m_DateReference ;
}
}

public DateTime DateStart
{
get
{
return m_DateStart;
}
set
{
m_DateStart = value;

m_IsDateStartAv ailable = true;
}
}

public DateTime DateFinish
{
get
{
return m_DateFinish;
}
set
{
m_DateFinish = value;

m_IsDateFinishA vailable = true;
}
}

public bool IsDateStartAvai lable
{
get
{
return m_IsDateStartAv ailable;
}
}

public bool IsDateFinishAva ilable
{
get
{
return m_IsDateFinishA vailable;
}
}

public bool IsCustomBuilt
{
get
{
return Type == ProductType.Cus tomizedProduct? true:false;
}
}

public bool IsGeneralBuilt
{
get
{
return Type == ProductType.Gen eralizedProduct ?true:false;
}
}

public bool Open(string id)
{
SqlCommand cmdSql = new SqlCommand("sel ect * from mstrproducts where
pk_product_id=' "+id+"'", Connection);

try
{
OpenConnection( );

SqlDataReader dr = cmdSql.ExecuteR eader();

if (dr.Read())
{
m_AutoIndex = DataConverter.T oLong(dr["auto_index "].ToString());
m_SerialNumber = dr["pk_product _id"].ToString();
m_DateReference =
Convert.ToDateT ime(dr["date_reference "].ToString());
Title = dr["title"].ToString();

if (!dr.IsDBNull(4 ))
{
DateStart = Convert.ToDateT ime(dr["date_start "].ToString());

m_IsDateStartAv ailable = true;
}
else
m_IsDateStartAv ailable = false;

if (!dr.IsDBNull(5 ))
{
DateFinish = Convert.ToDateT ime(dr["date_finis h"].ToString());

m_IsDateFinishA vailable = true;
}
else
m_IsDateFinishA vailable = false;

Type =
DataConverter.T oBoolean(dr["product_ty pe"].ToString())?Pr oductType.Gener alizedProduct:P roductType.Cust omizedProduct;

Version = dr["version"].ToString();
Build = dr["build"].ToString();
Notes = dr["notes"].ToString();
Features = dr["features"].ToString();
SystemRequireme nts = dr["system_require ments"].ToString();
PreRequisites = dr["prerequisi tes"].ToString();
Status = DataConverter.T oBoolean(dr["status"].ToString());
}
}
catch(Exception ex)
{
Console.WriteLi ne(ex.ToString( ));

return false;
}
finally
{
CloseConnection ();
}

return true;
}

internal bool Save()
{
SqlCommand cmdSql = new SqlCommand("Reg isterProducts", Connection);
cmdSql.CommandT ype = CommandType.Sto redProcedure;

if (m_SerialNumber .Trim().Length< =0) m_SerialNumber = _NewID;

cmdSql.Paramete rs.Add(new SqlParameter("@ product_id",
SqlDbType.VarCh ar, 10)).Value = SerialNumber;
cmdSql.Paramete rs.Add(new SqlParameter("@ date_reference" ,
SqlDbType.Small DateTime)).Valu e =
Convert.ToDateT ime(DateReferen ce.ToShortDateS tring());
cmdSql.Paramete rs.Add(new SqlParameter("@ title", SqlDbType.VarCh ar,
150)).Value = Title;

if (IsDateStartAva ilable) cmdSql.Paramete rs.Add(new
SqlParameter("@ date_start", SqlDbType.Small DateTime)).Valu e =
DateStart;
if (IsDateFinishAv ailable) cmdSql.Paramete rs.Add(new
SqlParameter("@ date_finish", SqlDbType.Small DateTime)).Valu e =
DateFinish;

cmdSql.Paramete rs.Add(new SqlParameter("@ product_type",
SqlDbType.Bit)) .Value = (Type == ProductType.Gen eralizedProduct ?0:1);
cmdSql.Paramete rs.Add(new SqlParameter("@ version",
SqlDbType.VarCh ar, 15)).Value = Version;
cmdSql.Paramete rs.Add(new SqlParameter("@ build", SqlDbType.VarCh ar,
15)).Value = Build;
cmdSql.Paramete rs.Add(new SqlParameter("@ notes", SqlDbType.NVarC har,
500)).Value = Notes;
cmdSql.Paramete rs.Add(new SqlParameter("@ features",
SqlDbType.NVarC har, 500)).Value = Features;
cmdSql.Paramete rs.Add(new SqlParameter("@ system_requirem ents",
SqlDbType.NVarC har, 500)).Value = SystemRequireme nts;
cmdSql.Paramete rs.Add(new SqlParameter("@ prerequisites",
SqlDbType.NVarC har, 500)).Value = PreRequisites;
cmdSql.Paramete rs.Add(new SqlParameter("@ status",
SqlDbType.Bit)) .Value = (Status?1:0);

try
{
OpenConnection( );

cmdSql.ExecuteN onQuery();
}
catch(Exception ex)
{
Console.WriteLi ne(ex.ToString( ));

return false;
}

return true;
}

internal bool Delete()
{
return false;
}

public static bool operator == (CProductInfo product1, CProductInfo
product2)
{
return product1.Equals (product2);
}

public static bool operator != (CProductInfo product1, CProductInfo
product2)
{
return (!product1.Equa ls(product2));
}

public override bool Equals(object obj)
{
if (!(obj is CProductInfo)) return false;
return this==(CProduct Info)obj;
}

public override int GetHashCode()
{
return base.GetHashCod e ();
}

public override string ToString()
{
return base.ToString ();
}

}
}

Jun 29 '06 #1
3 1527
Constantine wrote:
Hi, I have developed one class called CProductInfo providing == and !=
operator features. I have one problem.

When I use this class in my program, say

CProductInfo product = null;

and later, when i check for emptiness,

if (product==null)

it returns false as if the product instance is not empty.

I tried various ways to eliminate this run-time error, but it just does
not happen. Also I don't think there is use full tips on net for this.


It's not clear what runtime error you're talking about. However,
general rules:

o Check whether you've been passed null (using object.Referenc eEquals)
in the Equals method.
o Use object.Referenc eEquals to check against a null reference for both
parameters in your == and != overloads, in order to avoid
NullReferenceEx ceptions.

Jon

Jun 29 '06 #2
Hi,

Next time just post the relevant code.
No idea what error are you talking, unless that you have something like:

CProductInfo product = null;
if (product==null) product = new CProductInfo ();

product.SomeAct ion();
Of course as you are seeing the if is always false and therefore the
instance may never be initialized.
**** update ****
ok, I think I know where the error is, it's in :

public static bool operator == (CProductInfo product1, CProductInfo
product2)
{
return product1.Equals (product2);
}

you are presuming that the first argument of "==" is an initialized instance
when it's not there you will get a NullReference Exception.
**** end of update ****

See Jon's comments to how to do it.

IMO it's not a very good idea overload == , the operator has a VERY CLEAR
meaning of comparing references, not members's values of those instances.

WARNING:

Also you may be getting in an infinite recursion, you call Equals from "=="
and inside Equals you again call "=="

--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Jun 29 '06 #3
Constantine wrote:
Hi, I have developed one class called CProductInfo providing == and !=
operator features. I have one problem.

When I use this class in my program, say

CProductInfo product = null;

and later, when i check for emptiness,

if (product==null)

it returns false as if the product instance is not empty.

I tried various ways to eliminate this run-time error, but it just does
not happen. Also I don't think there is use full tips on net for this.

Can someone help?

Thanks in advance - Rhonald

<snippedy-doo-dah>

Hi Rhonald,

You have a slight bug in your code, which I'm guessing hasn't surfaced
because you have a bit of exception handling somewhere.

You've got to make sure 'product1' in your operator overloads isn't null,
before you call the 'Equals' method.

--
Hope this helps,
Tom Spink
Jun 29 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5248
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that discussions of new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for currently. I've searched around for about the last too weeks and have read up on new and overloading it to some extent but...
34
6472
by: Pmb | last post by:
I've been working on creating a Complex class for my own learning purpose (learn through doing etc.). I'm once again puzzled about something. I can't figure out how to overload the assignment operator. Here's what I'm trying to do. I've defined class Complex as class Complex { friend ostream &operator<<( ostream &, Complex & ); public: Complex( float = 0.0, float = 0.0 );
16
3099
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class has two int memebers "dataA", "dataB". The derived class has an additional int member "dataC". I am simply trying to overload the + operator so that 'adding' two objects will sum up the corresponding int members.
2
2068
by: pmatos | last post by:
Hi all, I'm overloading operator<< for a lot of classes. The question is about style. I define in each class header the prototype of the overloading as a friend. Now, where should I define the overloading of operator<<. In the .cc of the respective class or in a file where I am overloading operator<< for all classes? Cheers,
2
1694
by: Constantine | last post by:
Hi, I have developed one class called CProductInfo providing == and != operator features. I have one problem. When I use this class in my program, say CProductInfo product = null; and later, when i check for emptiness, if (product==null)
5
2490
by: luca regini | last post by:
I have this code class M { ..... T operator()( size_t x, size_t y ) const { ... Operator overloading A ....} T& operator()( size_t x, size_t y )
5
3632
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), , ->, =. I wonder why there is such a restriction. Some tutorials say that 'new' and 'delete' can only be overloaded with static member functions, others say that all overloading function should be non-static. Then what is the fact, and why? ...
2
4443
by: Colonel | last post by:
It seems that the problems have something to do with the overloading of istream operator ">>", but I just can't find the exact problem. // the declaration friend std::istream & operator>(std::istream & in, const Complex & a); // the methods correspond to the friend std::istream & operator>(std::istream & in, const Complex & a) { std::cout << "real: ";
8
2977
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular, operator =, operator, operator(), and operator-must be nonstatic member function; this ensures that their first operands will be lvalues". I know that these operators must be nonstatic member functions, but why this ensure their first operands will...
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10155
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.