I just one to make sure no one will derive from my non-polymorphic class, so I used following syntax:
class Foo final
{
Foo();
~Foo(); // not virtual
void bar();
};
In The C++ programming language I read that final can be used together with override for classes containing virtual member functions. I tried my code sample in VS 2013 and it compiles without any warning.
Is it allowed to use keyword final for non-polymorphic classes to prevent derivation from the class ? Does the keyword override make sense with non-polymorphic classes ?
The C++ grammar allows final to appear in two different places. One is a class-virt-specifier which can appear after the class name in a class declaration, which is how you've used it. Despite the name, using a class-virt-specifer has nothing to do with virtual functions and is allowed in non-polymorphic classes.
The other place it can be used is a virt-specifier on a member function. If present, a virt-specifer sequence consists of one or both of final and override, but is only allowed on virtual functions (9.2 [class.mem] "A virt-specifier-seq shall contain at most one of each virt-specifier. A virt-specifier-seq shall appear only in the declaration of a virtual member function (10.3)."). So override can only be used on virtual functions, so cannot be used in non-polymorphic types.
yes it is allowed even if your class is not virtual:
from cppreference:
http://en.cppreference.com/w/cpp/language/final
When used in a class definition, final specifies that this class may
not appear in the base-specifier-list of another class definition (in
other words, cannot be derived from).
The override keyword on the other hand makes no sense for non polymorphic classes.
Related
I'll start by saying that I'm working off the assumption that static array initializers are turned into private nested classes by the compiler, usually with names like __StaticArrayInitTypeSize=12. As I understand it, having read this extremely informative article, these private classes are value types, and they aren't tagged with the CompilerGeneratedAttribute class.
I'm working on a project that needs to process certain types and ignore others.
I have to be able to process custom struct types, which, like the generated static array initializer classes, are value types. I must ignore the generated static array initializer classes. I also must ignore enumerations and delegates.
I'm pulling these classes with Linq, like so:
var typesToProcess = allTypes.Where(type => !type.IsEnum &&
!type.IsArray &&
!type.IsSubclassOf(typeof(Delegate)));
I'm fairly sure that the IsArray property isn't what I think it is. At any rate, the generated static array initializer class still shows up in the typesToProcess Enumerable.
Has anyone else dealt with this? How can I discern the difference between a custom struct and a generated static array initializer class? I could hack it by doing a string comparison of the type name against __StaticArrayInitTypeSize, but is there a cleaner solution?
Well, having just tried it myself with the C# 4 compiler, I got an internal class called <PrivateImplementationDetails>{D1E23401-19BC-4B4E-8CC5-2C6DDEE7B97C} containing a private nested struct called __StaticArrayInitTypeSize=12.
The class contained an internal static field of the struct type called $$method0x6000001-1. The field itself was decorated with CompilerGeneratedAttribute.
The problem is that all of this is implementation-specific. It could change in future releases, or it could be different from earlier releases too.
Any member name containing <, > or = is an "unspeakable" name which will have been generated by the compiler, so you can view that as a sort of implicit CompilerGenerated, if that's any use. (There are any number of other uses for such generated types though.)
I've read about various COM design patterns detailed in COM Programmer's Cookbook as well some of related SO threads, notably the thread discussing composition vs. multiple inheritance. Possibly because I'm too new to both C++ and COM, I may be missing the points made in various sources so here's my question expressed in single sentence:
Can I extend an interface generated by MIDL for DLL's internal use and if so, how do I handle the diamond problem/parallel hierarchy correctly given MIDL/COM limitation?
The dirty details...
Hopefully to help other pinpoint where my confusion may be, here are my assumptions:
1) COM does not support virtual inheritance, and only allows for multiple inheritance via interfaces only.
2) Even though COM cannot see it, it should not be illegal for me to use unsupported C++ inheritance as long I do not expect it to be directly exposed by COM.
3) Because MIDL only allows single inheritance of interfaces, if I have a parallel hierarchy, I need to aggregate them for the coclass.
4) MIDL does not appear to declare the coclass itself, so I would need to write a .h file declaring the actual class and there, I may extend as needed with understanding COM consumers cannot use it (and that's OK).
What I want to do is have a base object (I've not decided yet whether it'll be abstract or not though I think it will be for now) that handles most of implementation details and delegate some specific functionality to subclasses. The client would typically use the subclasses. So,
project.idl
import "oaidl.idl"
import "ocidl.idl"
[
object,
uuid(...),
dual,
oleautomation
]
interface IBase : IDispatch {
//stuff I want to show to COM
};
[
object,
uuid(...),
dual,
oleautomation
]
interface IChild1 : IBase {
//stuff (in addition to base) I want to show to COM
};
[
object,
uuid(...),
dual,
oleautomation
]
interface IChild2 : IBase {
//stuff (in addition to base) I want to show to COM
};
[
uuid(...),
version(...),
]
library myproject {
importlib("stdole32.tlb");
interface IBase;
interface IChild1;
interface IChild2;
[
uuid(...),
]
coclass Base {
[default]interface IBase;
interface IOle*; //include other IOle* interfaces required for the functionality
};
[
uuid(...),
]
coclass Child1 {
[default]interface IChild1;
interface IOle*; //those are delegated to the base members
};
[
uuid(...),
]
coclass Child2 {
[default]interface IChild2;
interface IOle*; //those are delegated to the base members
};
};
base.h
#include base_h.h //interfaces generated by MIDL
// I assume I need to re-include IOle* because IBase has no relationship
// and C++ wouldn't know that I want the object base to also have those
// interfaces...
class base : public IBase,
public IOle* {
//handle all IUnknown, IDispatch and other IOle* stuff here
//as well as the common implementations as appropriate
};
child1.h
#include base.h
//I'm not sure if I need to re-include the IOle* interfaces...
//I also assume that by inheriting base, child1 also inherits its interface
class Child1 : public Base,
public IChild1 {
//specific details only, let base handle everything else.
};
child2.h
#include base.h
//I'm not sure if I need to re-include the IOle* interfaces...
class Child2 : public Base,
public IChild2 {
//specific details only, let base handle everything else.
};
Conceptually, creating a new child* object would always imply a creation of base object because base would be required to handle the implementation details, so I thought it's also appropriate to have the base take care of the QueryInterface & Reference counting, but I get confused on the following points:
1) compiler complains about members being ambiguous due to parallel hierarchy; IUnknown is re-implemented several times from my custom interface and from the additional IOle* interfaces. Documentations suggests that it is expected that only one implementation per object is actually needed but I'm not clear how I'd address the compiler's issues and I feel that doing a casting is somehow wrong? I also wonder if I am supposed to have all interfaces be inherited virtually which seems to be valid for C++, though COM wouldn't have no such understanding but it shouldn't care either(?).
2) However, if I do declare all of inherited interfaces as virtual in the .h files, compiler then complains that inherited members are not allowed when I try to implement QueryInterface in the Base class.cpp. I've googled on that error but am not clear what it is trying to tell me here.
EDIT: I answered my own question. Intel had documentation for this error which I initially did not click on the link, assuming that it may not apply to Visual Studio. I wish I did anyway but now I understand why I was getting this error since I was trying to do all implementation in Base::, rather than IUnknown:: or IDispatch::. This now begs a new question which may clarify my original & main question -- how do I defer the implementation from IUnknown (and others) to Base and work only from Base, if that is even possible? It seems that if I just use IUnknown::xxx, it no longer can access the Base's private members, which seems sane thing to expect so that may not be what I want. I tried declaring all other interfaces except base's own as virtual, but that didn't really take. (Again, it may be my inexperience not seeing the obvious solution.)
3) Base's QueryInterface cannot cast base to a child, which is a reasonable complaint, so I assume I have to reimplement the QI for all children anyway but I can delegate back to base's QI once I determine the requested interfaces isn't the child's. Bizarrely, the compiler insists that the child* class are abstract due to missing members for IUnknown & IDispatch, but didn't the base already implement and thus the child should have those members as well?
The various compiler errors makes me worry that my inexperience with either or both of language & framework is leading me to make a flawed assumptions about how I can design the COM objects & inheritance hierarchy and implementation details and I'm decidedly missing something here. Any pointers, even a slap on the head would be much appreciated.
Thanks!
You've got the right idea here, all you're missing is tying up some loose ends in the most-derived class. As a COM developer, you expect all the AddRef/Release/QI impls on a class object to be the same; but the C++-oriented compiler doesn't know that, so is treating them as all being potentially separate. The two impls you have here are the one in Base and the ones in any interfaces you've added.
Setting the compiler straight here is pretty easy: in the most derived class, redefine all the IUnknown methods, and direct them to the appropriate base class - eg.
class ChildX: public Base,
public IChildA
... more COM interfaces if needed ...
{
...
// Direct IUnknown methods to Base which does the refcounting for us...
STDMETHODIMP_(ULONG) AddRef() { return Base::AddRef(); }
STDMETHODIMP_(ULONG) Release() { return Base::Release(); }
... suggest implementing QI explicitly here.
}
This basically says that all methods called AddRef, regardless of how they ended up in ChildX, will get that specific implementation.
Its simplest to actually implement QI outright here, and only delegate AddRef/Release to Base. (Technically, Base can cast to Child using static_cast, but you need to put the code in an function after Child has been fully defined; it's not recommended to do this, however, since there's rarely a good reason for a base class to know about the classes that derive from it.)
Other things to watch for: make sure that Base has a virtual dtor declared - even if just empty, so that when Base does a 'delete this' when the ref goes to 0, it will call the dtors in the derived classes and any resources that they have allocated get cleaned up appropriately. Also, be sure to get the ref counting correct, and thread-safe if needed; check with any good intro to COM book (eg "Inside Distributed COM", which, despite the name, starts off with plain COM) to see how other folk do this.
This is a very common idiom in COM, and many frameworks use either #define macros or a more-derived template class to add in the AddRef/Release/QI (as MFC does) at the most-derived class and then delegate those to a well-known base class that handles much of the housekeeping.
I am really really really new to all of this, and most of it is unexplored territory. Today I needed to create an anonymous class and put it to a list. I was trying to find how I can make a list of anonymous types, and found that I should make an extension method. I also already figured out an extension method should be in a static class. But what I haven't figured out yet is if there is some pattern that I should use? For now, I have made a static class in my App_Code folder named ExtensionMethods, but have no idea if I should put extension methods of all kinds of types in this class, or if I should make separate classes etc.
To my knowledge you can not implement extension methods for anonymous classes. And this makes sense as really and truly if the class has some semantics it should be made a named class.
To create a list of anonymous classes use this method:
public static List<T> CreateListFromType<T>(T anonType){
return new List<T>();
}
To use this method to create a list, do something like:
var list = CreateListFromType(new {A = default(int), B = default(int)});
Extension method is nothing more than easier-to-read static helper/utility methods. The way you organize them is the same principal as how you organize your normal classes. If you think those should stays together, then try to give them a meaningful, general enough name as the class name. Once you found your class name cannot include what that method doing, then you know that method should belongs to other places.
Firstly extension methods are normal static methods declared like this -
void MyExtension(this MyTarget target, int myparam){ ..
After this the C# compiler adds some syntactic sugar letting you call this method as
target.MyExtension(myparam);
The compiler will replace all these calls with
MyStaticClass.MyExtension(target, myparam);
The important thing is that an extension method is a normal static method. You should follow following guidelines while creating them -
Try to group extension methods for each target class in a separate static class and name it appropriately as Extensions.
Create a new namespace in your application for Extension methods such as MyAppExtensions and keep your static classes inside this namespace. This will keep the coder from misunderstanding them as Extension method and accidentally using them as instance methods.
Make these naming conventions for namespaces and static classes of Extension methods as a standard in the team.
In your extension method check if the first parameter is null and take appropriate action. If you do not then it will be possible to call the method with target being null and may result in unexpected behavior. If the first parameter is allowed to be null then document it clearly.
Consciously decide if it is correct to create and extension method or instance method will be better.
Be careful that the extension method names do not clash with instance method names or other existing extension method names for this class. Following point 1, 2 and 3 will help you achieve this.
I learnt these from Jon Skeet's C# In Depth. You should read it too.
This is how you create a list of an anonymous class.
var anonList = new[]{
new {Foo = "foo", Bar = 2},
new { Foo = "bar", Bar = 3},
}.ToList();
It has nothing to do with writing extension methods.
Edit:
In fact you will have a hard time to use extension methods to create anonymous types since anonymous types can not be used as method parameters or return type.
Edit2:
If you want to convert a list of anonymous types to a list of specific types you can use Select:
class MyClass
{
public string Prop1 {get;set;}
public int Prop2 {get;set;}
}
List<MyClass> myList = anonList.Select(x => new MyClass(){Prop1 = Foo, Prop2 = Bar}).ToList();
I use to put anonymous to DataTable. Due to it's limitation, DataTable provide more functionality such as serialization.
When you add a new method to a class where do you put it? At the end of the class...the top? Do you organize methods into specific groupings? Sorted alphabetically?
Just looking for general practices in keeping class methods organized.
Update When grouped where do you add the new method in the group? Just tack on the end or do you use some sort of sub-grouping, sorting?
Update 2 Mmmm...guess the question isn't as clear as I thought. I'm not really looking for class organization. I'm specifically interested in adding a new method to an existing class. For example:
public class Attendant
{
public void GetDrinks(){}
public void WelcomeGuests(){}
public void PickUpTrask(){}
public void StrapIn(){}
}
Now we're going to add a new method PrepareForCrash(). Where does it go? At the top of the list, bottom, alphabetically or near the StrapIn() method since it's related.
Near "StrapIn" because it's related. That way if you refactor later, all related code is nearby.
Most code editors allow you to browse method names alphabetically in another pane, so organizing your code functionally makes sense within the actual code itself. Group functional methods together, makes life easier when navigating through the class.
For goodness sake, not alphabetically!
I tend to group my functions in the order I expect them to be called during the life of the object, so that a top to bottom read of the header file tends to explain the operation of the class.
I think it's a personal choice.
However I like to organise my classes as such.
public class classname
{
<member variables>
<constructors>
<destructor>
<public methods>
<protected methods>
<private methods>
}
The reason for this is as such.
Member variables at the top
To see what member variables exist and if they are initialised.
Constructors
To see if the member variables are setup/initialised as well as what are all the construction options for the class.
Destructor
To see the how the class is cleaned up and verify it with the constructors and member variables.
Public methods
To see what are the available contracts callers of the object can use.
Protected methods
To see what inherited classes would be using.
Private methods
As it's information about the internals of the class if you needed to know about the internals you can just scroll straight to the end quickly. But to know the interface for the class it's all at the start.
UPDATE - Based on OP's update
Logically a good way would be to organise the methods by categories of what they do.
This way you get the readabilty of categorising your methods as well as the alphabetical search from you IDE (provided this is in your IDE).
However in a practical sense I think placing the methods at the end of that section is the best way. It would be quite hard to continually police where each method goes, as it's subjective, for every method if the code is shared by more than yourself.
If you were to make this a standard it'd be quite hard to provide the boundaries for where to put each method.
What I like about C# and VB.net is the ability to use #region tags, so generally my classes look like this
class MyClass
{
#region Constructors
public MyClass()
{
}
public MyClass(int x)
{
_x = x;
}
#endregion
#region Members
private int _x;
#endregion
#region methods
public void DoSomething()
{
}
#endregion
#region Properties
public int Y {get; private set;}
#endregion
}
So basically You put similar things together so you can collapse everything to definition and get to your stuff really faster.
Generally, it depends on the existing grouping; if there's an existing grouping that the new method fits into, I'll put it there. For example, if there's a grouping of operators, I'll put the new method with the operators if it's an operator.
Of course, if there is no good grouping, adding a method may suggest a new grouping; I treat that as an opportunity for refactoring, and try to regroup the existing operators where reasonable.
I organize all methods into regions like public methods, private methods or sometimes by features like Saving methods, etc..
IMHO:
If you organize your methods alphabetically, put a new one depends on its name. Otherwise put it at the bottom of related group. This helps to know, what method is newer. The bigger problem is how to organize methods in groups, e.g. depend on what properties, but this is more individual for everyone and depends on a specific class.
I have found that there is generally a singe type or namespace that takes in any particular enum as a parameter and as a result I have always defined those enums there. Recently though, I had a co-worker make a big deal about how that was a stupid thing to do, and you should always have an enum namespace at the root of your project where you define everyone of your enum types.
Where is the best place to locate enum types?
Why treat enums differently to other types? Keep them in the same namespace as they're likely to be used - and assuming they're going to be used by other classes, make them top-level types in their own files.
The only type of type which I do commonly clump together is delegates - I sometimes have a Delegates.cs file with a bunch of delegates in. Less so with .NET 3.5 and Func/Action, mind you.
Also, namespaces are for separation of things that belong together logically. Not all classes belong in the same namespace just because they are classes. Likewise, not all enums belong in the same namespace just because they are enums. Put them with the code they logically belong in.
I generally try to put all my different types (classes, interfaces and enums) in their own files, regardless of how small they are. It just makes it much easier to find and manage the file they're in, especially if you don't happen to be in Visual Studio and have the "go to definition" feature available. I've found that nearly every time I've put a "simple" type like that in another class, I end up either adding on to it later on, or reusing it in a way that it no longer makes sense for it to not have its own file.
As far as which namespace, it really depends on the design of whatever you're developing. In general, I try to mimic the .NET framework's convention.
I try to put everything associated with a class in the class. That includes not just enums, but also constants. I don't want to go searching elsewhere for the file or class containing the enums. In a large app with lots of classes and folders, it wouldn't always be obvious where to put the enum file so it would be easy to find.
If the enum if used in several closely-related classes, you could create a base class so that the common types like enums are shared there.
Of course, if an enum is really generic and widely used, you may want to create a separate class for them, along with other generic utilities.
I think you put Enums and Constants in the class that consumes them or that uses them to control code decisions the most and you use code completion to find them. That way you don't have to remember where they are, they are associated with the class. So for example if I have a ColoredBox class then I don't have to think about where they are at. They would be part of ColoredBox. ColoredBox.Colors.Red, ColoredBox.Colors.Blue etc. I
I think of the enum and constant as a property or description of that class.
If it used by multiple classes and no one class reigns supreme then it is appropriate to have an enum class or constants class.
This follows rules of encapsulation. Isolating properties from dissimilar classes. What if you decide to change the RGB of Red in Cirle objects but
you don't want to change the red for ColoredBox objects? Encapsulating their properties enables this.
I use nested namespaces for this. I like them better than putting the enum within a class because outside of the class you have to use the full MyClass::MyEnum usage even if MyEnum is not going to clash with anything else in scope.
By using a nested namespace you can use the "using" syntax. Also I will put enums that relate to a given subsystem in their own file so you don't get dependency problems of having to include the world to use them.
So in the enum header file you get:
// MyEnumHeader.h
// Consolidated enum header file for this dll,lib,subsystem whatever.
namespace MyApp
{
namespace MyEnums
{
enum SomeEnum { EnumVal0, EnumVal1, EnumVal2 };
};
};
And then in the class header file you get:
// MyInterfaceHeader.h
// Class interfaces for the subsystem with all the expected dependencies.
#include "MyEnumHeader.h"
namespace MyApp
{
class MyInterface
{
public:
virtual void DoSomethingWithEnumParam (MyEnums::SomeEnum enumParam) = 0;
};
};
Or use as many enum header files as makes sense. I like to keep them separate from the class headers so the enums can be params elsewhere in the system without needing the class headers. Then if you want to use them elsewhere you don't have to have the encapsulating class defs as you would if the enums were declared within the classes.
And as mentioned before, in the outer code you can use the following:
using namespace MyApp::MyEnums;
What environment?
In .NET I usually create an empty class file, rename it to MyEnum or whatever to indicate it holds my enum and just declare it in there.
If my enumeration has any chance of ever being used outside the class I intend to use it, I create a separate source file for the enum. Otherwise I will place it inside the class I intend to use it.
Usually I find that the enum is centered around a single class -- as a MyClassOptions type of thing.
In that case, I place the enum in the same file as MyClass, but inside the namespace but outside the class.
namespace mynamespace
{
public partial class MyClass
{
}
enum MyClassOptions
{
}
}
I tend to define them, where their use is evident in the evident. If I have a typedef for a struct that makes use of it for some reason...
typedef enum {
HI,
GOODBYE
} msg_type;
typdef struct {
msg_type type;
union {
int hivar;
float goodbyevar;
}
} msg;